Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 205be877b8 | |||
| 616a94fdc3 | |||
| a132861920 | |||
| 86b2935755 | |||
| 7ebdbe102c | |||
| 446ef9c467 | |||
| 2e261e1b91 | |||
| 31e75cd9e6 | |||
| cbd5d08101 | |||
| 9ce9931f86 | |||
| 379f41814a | |||
| 848b2d96ca | |||
| c09a5000b2 | |||
| 14739a19c7 |
@@ -1,369 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""gitea-merge-queue — conservative serialized merge bot for Gitea.
|
||||
|
||||
Gitea 1.22.6 has auto-merge (`pull_auto_merge`) but no GitHub-style merge
|
||||
queue. This script provides the missing serialized policy in user space:
|
||||
|
||||
1. Pick the oldest open PR carrying QUEUE_LABEL.
|
||||
2. Refuse to act unless main is green.
|
||||
3. Refuse fork PRs; the queue may only mutate same-repo branches.
|
||||
4. If the PR branch does not contain current main, call Gitea's
|
||||
/pulls/{n}/update endpoint and stop. CI must rerun on the updated head.
|
||||
5. If the updated PR head has all required contexts green, merge with the
|
||||
non-bypass merge actor token.
|
||||
|
||||
The script is intentionally one-PR-per-run. Workflow/cron concurrency should
|
||||
serialize invocations so two green PRs cannot merge against the same main.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _env(key: str, *, default: str = "") -> str:
|
||||
return os.environ.get(key, default)
|
||||
|
||||
|
||||
GITEA_TOKEN = _env("GITEA_TOKEN")
|
||||
GITEA_HOST = _env("GITEA_HOST")
|
||||
REPO = _env("REPO")
|
||||
WATCH_BRANCH = _env("WATCH_BRANCH", default="main")
|
||||
QUEUE_LABEL = _env("QUEUE_LABEL", default="merge-queue")
|
||||
HOLD_LABEL = _env("HOLD_LABEL", default="merge-queue-hold")
|
||||
UPDATE_STYLE = _env("UPDATE_STYLE", default="merge")
|
||||
REQUIRED_CONTEXTS_RAW = _env(
|
||||
"REQUIRED_CONTEXTS",
|
||||
default=(
|
||||
"CI / all-required (pull_request),"
|
||||
"sop-checklist / all-items-acked (pull_request)"
|
||||
),
|
||||
)
|
||||
|
||||
OWNER, NAME = (REPO.split("/", 1) + [""])[:2] if REPO else ("", "")
|
||||
API = f"https://{GITEA_HOST}/api/v1" if GITEA_HOST else ""
|
||||
|
||||
|
||||
class ApiError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class MergeDecision:
|
||||
ready: bool
|
||||
action: str
|
||||
reason: str
|
||||
|
||||
|
||||
def _require_runtime_env() -> None:
|
||||
for key in ("GITEA_TOKEN", "GITEA_HOST", "REPO", "WATCH_BRANCH", "QUEUE_LABEL"):
|
||||
if not os.environ.get(key):
|
||||
sys.stderr.write(f"::error::missing required env var: {key}\n")
|
||||
sys.exit(2)
|
||||
if UPDATE_STYLE not in {"merge", "rebase"}:
|
||||
sys.stderr.write("::error::UPDATE_STYLE must be merge or rebase\n")
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
def api(
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
body: dict | None = None,
|
||||
query: dict[str, str] | None = None,
|
||||
expect_json: bool = True,
|
||||
) -> tuple[int, Any]:
|
||||
url = f"{API}{path}"
|
||||
if query:
|
||||
url = f"{url}?{urllib.parse.urlencode(query)}"
|
||||
data = None
|
||||
headers = {
|
||||
"Authorization": f"token {GITEA_TOKEN}",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, method=method, data=data, headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
raw = resp.read()
|
||||
status = resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
raw = exc.read()
|
||||
status = exc.code
|
||||
|
||||
if not (200 <= status < 300):
|
||||
snippet = raw[:500].decode("utf-8", errors="replace") if raw else ""
|
||||
raise ApiError(f"{method} {path} -> HTTP {status}: {snippet}")
|
||||
if not raw:
|
||||
return status, None
|
||||
try:
|
||||
return status, json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
if expect_json:
|
||||
raise ApiError(f"{method} {path} -> HTTP {status} non-JSON: {exc}") from exc
|
||||
return status, {"_raw": raw.decode("utf-8", errors="replace")}
|
||||
|
||||
|
||||
def required_contexts(raw: str) -> list[str]:
|
||||
return [part.strip() for part in raw.split(",") if part.strip()]
|
||||
|
||||
|
||||
def status_state(status: dict) -> str:
|
||||
return str(status.get("status") or status.get("state") or "").lower()
|
||||
|
||||
|
||||
def latest_statuses_by_context(statuses: list[dict]) -> dict[str, dict]:
|
||||
latest: dict[str, dict] = {}
|
||||
for status in statuses:
|
||||
context = status.get("context")
|
||||
if isinstance(context, str) and context not in latest:
|
||||
latest[context] = status
|
||||
return latest
|
||||
|
||||
|
||||
def required_contexts_green(
|
||||
latest_statuses: dict[str, dict],
|
||||
contexts: list[str],
|
||||
) -> tuple[bool, list[str]]:
|
||||
missing_or_bad: list[str] = []
|
||||
for context in contexts:
|
||||
status = latest_statuses.get(context)
|
||||
state = status_state(status or {})
|
||||
if state != "success":
|
||||
missing_or_bad.append(f"{context}={state or 'missing'}")
|
||||
return not missing_or_bad, missing_or_bad
|
||||
|
||||
|
||||
def label_names(issue: dict) -> set[str]:
|
||||
return {
|
||||
label["name"]
|
||||
for label in issue.get("labels", [])
|
||||
if isinstance(label, dict) and isinstance(label.get("name"), str)
|
||||
}
|
||||
|
||||
|
||||
def choose_next_queued_issue(
|
||||
issues: list[dict],
|
||||
*,
|
||||
queue_label: str,
|
||||
hold_label: str = "",
|
||||
) -> dict | None:
|
||||
candidates = []
|
||||
for issue in issues:
|
||||
labels = label_names(issue)
|
||||
if queue_label not in labels:
|
||||
continue
|
||||
if hold_label and hold_label in labels:
|
||||
continue
|
||||
if "pull_request" not in issue:
|
||||
continue
|
||||
candidates.append(issue)
|
||||
candidates.sort(key=lambda issue: (issue.get("created_at") or "", int(issue["number"])))
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
|
||||
def pr_contains_base_sha(commits: list[dict], base_sha: str) -> bool:
|
||||
for commit in commits:
|
||||
sha = commit.get("sha") or commit.get("id")
|
||||
if sha == base_sha:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def pr_has_current_base(pr: dict, commits: list[dict], main_sha: str) -> bool:
|
||||
if pr.get("merge_base") == main_sha:
|
||||
return True
|
||||
return pr_contains_base_sha(commits, main_sha)
|
||||
|
||||
|
||||
def evaluate_merge_readiness(
|
||||
*,
|
||||
main_status: dict,
|
||||
pr_status: dict,
|
||||
required_contexts: list[str],
|
||||
pr_has_current_base: bool,
|
||||
) -> MergeDecision:
|
||||
main_state = str(main_status.get("state") or "").lower()
|
||||
if main_state != "success":
|
||||
return MergeDecision(False, "pause", f"main status is {main_state or 'missing'}")
|
||||
if not pr_has_current_base:
|
||||
return MergeDecision(False, "update", "PR head does not contain current main")
|
||||
|
||||
pr_state = str(pr_status.get("state") or "").lower()
|
||||
if pr_state != "success":
|
||||
return MergeDecision(False, "wait", f"PR combined status is {pr_state or 'missing'}")
|
||||
|
||||
latest = latest_statuses_by_context(pr_status.get("statuses") or [])
|
||||
ok, missing_or_bad = required_contexts_green(latest, required_contexts)
|
||||
if not ok:
|
||||
return MergeDecision(False, "wait", "required contexts not green: " + ", ".join(missing_or_bad))
|
||||
return MergeDecision(True, "merge", "ready")
|
||||
|
||||
|
||||
def get_branch_head(branch: str) -> str:
|
||||
_, body = api("GET", f"/repos/{OWNER}/{NAME}/branches/{branch}")
|
||||
commit = body.get("commit") if isinstance(body, dict) else None
|
||||
sha = commit.get("id") if isinstance(commit, dict) else None
|
||||
if not isinstance(sha, str) or len(sha) < 7:
|
||||
raise ApiError(f"branch {branch} response missing commit id")
|
||||
return sha
|
||||
|
||||
|
||||
def get_combined_status(sha: str) -> dict:
|
||||
_, body = api("GET", f"/repos/{OWNER}/{NAME}/commits/{sha}/status")
|
||||
if not isinstance(body, dict):
|
||||
raise ApiError(f"status for {sha} response not object")
|
||||
return body
|
||||
|
||||
|
||||
def list_queued_issues() -> list[dict]:
|
||||
_, body = api(
|
||||
"GET",
|
||||
f"/repos/{OWNER}/{NAME}/issues",
|
||||
query={
|
||||
"state": "open",
|
||||
"type": "pulls",
|
||||
"labels": QUEUE_LABEL,
|
||||
"limit": "50",
|
||||
},
|
||||
)
|
||||
if not isinstance(body, list):
|
||||
raise ApiError("queued issues response not list")
|
||||
return body
|
||||
|
||||
|
||||
def get_pull(pr_number: int) -> dict:
|
||||
_, body = api("GET", f"/repos/{OWNER}/{NAME}/pulls/{pr_number}")
|
||||
if not isinstance(body, dict):
|
||||
raise ApiError(f"PR #{pr_number} response not object")
|
||||
return body
|
||||
|
||||
|
||||
def get_pull_commits(pr_number: int) -> list[dict]:
|
||||
_, body = api("GET", f"/repos/{OWNER}/{NAME}/pulls/{pr_number}/commits")
|
||||
if not isinstance(body, list):
|
||||
raise ApiError(f"PR #{pr_number} commits response not list")
|
||||
return body
|
||||
|
||||
|
||||
def post_comment(pr_number: int, body: str, *, dry_run: bool) -> None:
|
||||
print(f"::notice::comment PR #{pr_number}: {body.splitlines()[0][:160]}")
|
||||
if dry_run:
|
||||
return
|
||||
api("POST", f"/repos/{OWNER}/{NAME}/issues/{pr_number}/comments", body={"body": body})
|
||||
|
||||
|
||||
def update_pull(pr_number: int, *, dry_run: bool) -> None:
|
||||
print(f"::notice::updating PR #{pr_number} with base branch via style={UPDATE_STYLE}")
|
||||
if dry_run:
|
||||
return
|
||||
api(
|
||||
"POST",
|
||||
f"/repos/{OWNER}/{NAME}/pulls/{pr_number}/update",
|
||||
query={"style": UPDATE_STYLE},
|
||||
expect_json=False,
|
||||
)
|
||||
|
||||
|
||||
def merge_pull(pr_number: int, *, dry_run: bool) -> None:
|
||||
payload = {
|
||||
"Do": "merge",
|
||||
"MergeTitleField": f"Merge PR #{pr_number} via Gitea merge queue",
|
||||
"MergeMessageField": (
|
||||
"Serialized merge by gitea-merge-queue after current-main, "
|
||||
"SOP, and required CI checks were green."
|
||||
),
|
||||
}
|
||||
print(f"::notice::merging PR #{pr_number}")
|
||||
if dry_run:
|
||||
return
|
||||
api("POST", f"/repos/{OWNER}/{NAME}/pulls/{pr_number}/merge", body=payload, expect_json=False)
|
||||
|
||||
|
||||
def process_once(*, dry_run: bool = False) -> int:
|
||||
contexts = required_contexts(REQUIRED_CONTEXTS_RAW)
|
||||
main_sha = get_branch_head(WATCH_BRANCH)
|
||||
main_status = get_combined_status(main_sha)
|
||||
if str(main_status.get("state") or "").lower() != "success":
|
||||
print(f"::notice::queue paused: {WATCH_BRANCH}@{main_sha[:8]} is not green")
|
||||
return 0
|
||||
|
||||
issue = choose_next_queued_issue(
|
||||
list_queued_issues(),
|
||||
queue_label=QUEUE_LABEL,
|
||||
hold_label=HOLD_LABEL,
|
||||
)
|
||||
if not issue:
|
||||
print("::notice::merge queue empty")
|
||||
return 0
|
||||
|
||||
pr_number = int(issue["number"])
|
||||
pr = get_pull(pr_number)
|
||||
if pr.get("state") != "open":
|
||||
print(f"::notice::PR #{pr_number} is not open; skipping")
|
||||
return 0
|
||||
if pr.get("base", {}).get("ref") != WATCH_BRANCH:
|
||||
post_comment(pr_number, f"merge-queue: skipped; base branch is not `{WATCH_BRANCH}`.", dry_run=dry_run)
|
||||
return 0
|
||||
if pr.get("head", {}).get("repo_id") != pr.get("base", {}).get("repo_id"):
|
||||
post_comment(pr_number, "merge-queue: skipped; fork PRs are not supported by the serialized queue.", dry_run=dry_run)
|
||||
return 0
|
||||
|
||||
head_sha = pr.get("head", {}).get("sha")
|
||||
if not isinstance(head_sha, str) or len(head_sha) < 7:
|
||||
raise ApiError(f"PR #{pr_number} missing head sha")
|
||||
commits = get_pull_commits(pr_number)
|
||||
current_base = pr_has_current_base(pr, commits, main_sha)
|
||||
pr_status = get_combined_status(head_sha)
|
||||
decision = evaluate_merge_readiness(
|
||||
main_status=main_status,
|
||||
pr_status=pr_status,
|
||||
required_contexts=contexts,
|
||||
pr_has_current_base=current_base,
|
||||
)
|
||||
|
||||
print(f"::notice::PR #{pr_number} decision={decision.action}: {decision.reason}")
|
||||
if decision.action == "update":
|
||||
update_pull(pr_number, dry_run=dry_run)
|
||||
post_comment(
|
||||
pr_number,
|
||||
(
|
||||
f"merge-queue: updated this branch with `{WATCH_BRANCH}` at "
|
||||
f"`{main_sha[:12]}`. Waiting for CI on the refreshed head."
|
||||
),
|
||||
dry_run=dry_run,
|
||||
)
|
||||
return 0
|
||||
if decision.ready:
|
||||
latest_main_sha = get_branch_head(WATCH_BRANCH)
|
||||
if latest_main_sha != main_sha:
|
||||
print(
|
||||
f"::notice::main moved {main_sha[:8]} -> {latest_main_sha[:8]}; "
|
||||
"deferring to next tick"
|
||||
)
|
||||
return 0
|
||||
merge_pull(pr_number, dry_run=dry_run)
|
||||
return 0
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
args = parser.parse_args()
|
||||
_require_runtime_env()
|
||||
return process_once(dry_run=args.dry_run)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,114 +0,0 @@
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "gitea-merge-queue.py"
|
||||
spec = importlib.util.spec_from_file_location("gitea_merge_queue", SCRIPT)
|
||||
mq = importlib.util.module_from_spec(spec)
|
||||
sys.modules[spec.name] = mq
|
||||
spec.loader.exec_module(mq)
|
||||
|
||||
|
||||
def test_latest_statuses_dedupes_by_context_newest_first():
|
||||
statuses = [
|
||||
{"context": "CI / all-required (pull_request)", "status": "failure"},
|
||||
{"context": "sop-checklist / all-items-acked (pull_request)", "state": "success"},
|
||||
{"context": "CI / all-required (pull_request)", "status": "success"},
|
||||
]
|
||||
|
||||
latest = mq.latest_statuses_by_context(statuses)
|
||||
|
||||
assert latest["CI / all-required (pull_request)"]["status"] == "failure"
|
||||
assert latest["sop-checklist / all-items-acked (pull_request)"]["state"] == "success"
|
||||
|
||||
|
||||
def test_required_contexts_green_rejects_missing_and_pending():
|
||||
latest = mq.latest_statuses_by_context([
|
||||
{"context": "CI / all-required (pull_request)", "status": "success"},
|
||||
{"context": "sop-checklist / all-items-acked (pull_request)", "status": "pending"},
|
||||
])
|
||||
|
||||
ok, missing_or_bad = mq.required_contexts_green(
|
||||
latest,
|
||||
[
|
||||
"CI / all-required (pull_request)",
|
||||
"sop-checklist / all-items-acked (pull_request)",
|
||||
"qa-review / approved (pull_request)",
|
||||
],
|
||||
)
|
||||
|
||||
assert ok is False
|
||||
assert missing_or_bad == [
|
||||
"sop-checklist / all-items-acked (pull_request)=pending",
|
||||
"qa-review / approved (pull_request)=missing",
|
||||
]
|
||||
|
||||
|
||||
def test_choose_next_pr_sorts_by_queue_label_timestamp_then_number():
|
||||
issues = [
|
||||
{
|
||||
"number": 12,
|
||||
"pull_request": {},
|
||||
"labels": [{"name": "merge-queue"}],
|
||||
"created_at": "2026-05-13T05:00:00Z",
|
||||
"updated_at": "2026-05-13T06:00:00Z",
|
||||
},
|
||||
{
|
||||
"number": 9,
|
||||
"pull_request": {},
|
||||
"labels": [{"name": "merge-queue"}],
|
||||
"created_at": "2026-05-13T04:00:00Z",
|
||||
"updated_at": "2026-05-13T07:00:00Z",
|
||||
},
|
||||
{
|
||||
"number": 7,
|
||||
"labels": [{"name": "merge-queue"}],
|
||||
"created_at": "2026-05-13T03:00:00Z",
|
||||
},
|
||||
]
|
||||
|
||||
selected = mq.choose_next_queued_issue(issues, queue_label="merge-queue")
|
||||
|
||||
assert selected["number"] == 9
|
||||
|
||||
|
||||
def test_pr_needs_update_when_base_sha_absent_from_commits():
|
||||
commits = [
|
||||
{"sha": "head"},
|
||||
{"sha": "parent"},
|
||||
]
|
||||
|
||||
assert mq.pr_contains_base_sha(commits, "mainsha") is False
|
||||
assert mq.pr_contains_base_sha(commits, "parent") is True
|
||||
|
||||
|
||||
def test_merge_decision_requires_main_green_pr_green_and_current_base():
|
||||
required = ["CI / all-required (pull_request)"]
|
||||
main_status = {"state": "success", "statuses": []}
|
||||
pr_status = {
|
||||
"state": "success",
|
||||
"statuses": [{"context": "CI / all-required (pull_request)", "status": "success"}],
|
||||
}
|
||||
|
||||
decision = mq.evaluate_merge_readiness(
|
||||
main_status=main_status,
|
||||
pr_status=pr_status,
|
||||
required_contexts=required,
|
||||
pr_has_current_base=True,
|
||||
)
|
||||
|
||||
assert decision.ready is True
|
||||
assert decision.action == "merge"
|
||||
|
||||
|
||||
def test_merge_decision_updates_stale_pr_before_merge():
|
||||
decision = mq.evaluate_merge_readiness(
|
||||
main_status={"state": "success", "statuses": []},
|
||||
pr_status={"state": "success", "statuses": [{"context": "CI / all-required (pull_request)", "status": "success"}]},
|
||||
required_contexts=["CI / all-required (pull_request)"],
|
||||
pr_has_current_base=False,
|
||||
)
|
||||
|
||||
assert decision.ready is False
|
||||
assert decision.action == "update"
|
||||
@@ -1,51 +0,0 @@
|
||||
name: gitea-merge-queue
|
||||
|
||||
# External serialized merge queue for Gitea 1.22.6.
|
||||
#
|
||||
# Gitea's `pull_auto_merge` table is not a real merge queue: it does not
|
||||
# serialize green PRs against a freshly-tested latest main. This workflow runs
|
||||
# the user-space queue bot, one PR per tick, using the non-bypass merge actor.
|
||||
#
|
||||
# Queue contract:
|
||||
# - add label `merge-queue` to an open same-repo PR
|
||||
# - bot updates stale PR heads with current main, then waits for CI
|
||||
# - bot merges only when current main is green and required PR contexts pass
|
||||
# - add `merge-queue-hold` to pause a queued PR without removing it
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '*/5 * * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: gitea-merge-queue-${{ github.repository }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
queue:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Check out queue script from main
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
|
||||
- name: Process one queued PR
|
||||
env:
|
||||
# AUTO_SYNC_TOKEN is the devops-engineer persona PAT. It is the
|
||||
# non-bypass merge actor allowed by branch protection.
|
||||
GITEA_TOKEN: ${{ secrets.AUTO_SYNC_TOKEN }}
|
||||
GITEA_HOST: git.moleculesai.app
|
||||
REPO: ${{ github.repository }}
|
||||
WATCH_BRANCH: ${{ github.event.repository.default_branch }}
|
||||
QUEUE_LABEL: merge-queue
|
||||
HOLD_LABEL: merge-queue-hold
|
||||
UPDATE_STYLE: merge
|
||||
REQUIRED_CONTEXTS: >-
|
||||
CI / all-required (pull_request),
|
||||
sop-checklist / all-items-acked (pull_request)
|
||||
run: python3 .gitea/scripts/gitea-merge-queue.py
|
||||
@@ -66,27 +66,19 @@ jobs:
|
||||
# PR#372's ci.yml port used. Diffs against the PR base or the
|
||||
# previous push SHA, then matches against the wheel-relevant
|
||||
# path set.
|
||||
#
|
||||
# Root fix (mc#917): Gitea Actions does not expose github.event.before
|
||||
# as a ${{ }} template-expression that resolves in shell scripts for
|
||||
# push events (it becomes empty string). The env var GITHUB_EVENT_BEFORE
|
||||
# IS set by the runner for push events. Guard git cat-file with
|
||||
# `timeout 30` to prevent indefinite hangs on malformed BASE values.
|
||||
BASE="${GITHUB_BASE_REF:-${{ github.event.before }}}"
|
||||
if [ "${{ github.event_name }}" = "pull_request" ] && [ -n "${{ github.event.pull_request.base.sha }}" ]; then
|
||||
BASE="${{ github.event.pull_request.base.sha }}"
|
||||
else
|
||||
BASE="${GITHUB_EVENT_BEFORE:-}"
|
||||
fi
|
||||
if [ -z "$BASE" ] || echo "$BASE" | grep -qE '^0+$'; then
|
||||
# New branch or no previous SHA: treat as wheel-relevant.
|
||||
echo "wheel=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
if ! timeout 30 git cat-file -e "$BASE" 2>/dev/null; then
|
||||
if ! git cat-file -e "$BASE" 2>/dev/null; then
|
||||
git fetch --depth=1 origin "$BASE" 2>/dev/null || true
|
||||
fi
|
||||
if ! timeout 30 git cat-file -e "$BASE" 2>/dev/null; then
|
||||
echo "::notice::BASE=$BASE not in local clone (shallow fetch or pruned ref)"
|
||||
if ! git cat-file -e "$BASE" 2>/dev/null; then
|
||||
echo "wheel=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -11,9 +11,8 @@ name: Ops Scripts Tests
|
||||
# - `continue-on-error: true` on the job (RFC §1 contract).
|
||||
#
|
||||
# Runs the unittest suite for scripts/ on every PR + push that touches
|
||||
# anything under scripts/ or .gitea/scripts/. Kept separate from the main CI
|
||||
# so a script-only change doesn't trigger the heavier Go/Canvas/Python
|
||||
# pipelines.
|
||||
# anything under scripts/. Kept separate from the main CI so a script-only
|
||||
# change doesn't trigger the heavier Go/Canvas/Python pipelines.
|
||||
#
|
||||
# Discovery layout: tests sit alongside the code they test (see
|
||||
# scripts/ops/test_sweep_cf_decide.py for the pattern; scripts/
|
||||
@@ -28,13 +27,11 @@ on:
|
||||
branches: [main, staging]
|
||||
paths:
|
||||
- 'scripts/**'
|
||||
- '.gitea/scripts/**'
|
||||
- '.gitea/workflows/test-ops-scripts.yml'
|
||||
pull_request:
|
||||
branches: [main, staging]
|
||||
paths:
|
||||
- 'scripts/**'
|
||||
- '.gitea/scripts/**'
|
||||
- '.gitea/workflows/test-ops-scripts.yml'
|
||||
|
||||
env:
|
||||
@@ -56,8 +53,6 @@ jobs:
|
||||
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
||||
with:
|
||||
python-version: '3.11'
|
||||
- name: Install .gitea script test dependencies
|
||||
run: python -m pip install --quiet 'pytest==9.0.2' 'PyYAML==6.0.2'
|
||||
- name: Run scripts/ unittests (build_runtime_package, ...)
|
||||
# Top-level scripts/ tests live alongside their target file
|
||||
# (e.g. scripts/test_build_runtime_package.py exercises
|
||||
@@ -69,5 +64,3 @@ jobs:
|
||||
- name: Run scripts/ops/ unittests (sweep_cf_decide, ...)
|
||||
working-directory: scripts/ops
|
||||
run: python -m unittest discover -p 'test_*.py' -v
|
||||
- name: Run .gitea/scripts pytest suite
|
||||
run: python -m pytest .gitea/scripts/tests -q
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Unit tests for formatAuditRelativeTime — pure date formatter from AuditTrailPanel.
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { formatAuditRelativeTime } from "../AuditTrailPanel";
|
||||
|
||||
describe("formatAuditRelativeTime", () => {
|
||||
it('returns "just now" for timestamps within the last minute', () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const thirtySecAgo = new Date(now - 30_000).toISOString();
|
||||
expect(formatAuditRelativeTime(thirtySecAgo, now)).toBe("just now");
|
||||
});
|
||||
|
||||
it('returns "Xm ago" for timestamps within the last hour', () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const fiveMinAgo = new Date(now - 5 * 60_000).toISOString();
|
||||
expect(formatAuditRelativeTime(fiveMinAgo, now)).toBe("5m ago");
|
||||
});
|
||||
|
||||
it('returns "Xh ago" for timestamps within the last day', () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const threeHoursAgo = new Date(now - 3 * 3_600_000).toISOString();
|
||||
expect(formatAuditRelativeTime(threeHoursAgo, now)).toBe("3h ago");
|
||||
});
|
||||
|
||||
it("returns locale date string for timestamps older than 24h", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const twoDaysAgo = new Date(now - 2 * 86_400_000).toISOString();
|
||||
const result = formatAuditRelativeTime(twoDaysAgo, now);
|
||||
// Should be a date string (not "Xh ago" or "Xm ago")
|
||||
expect(result).not.toMatch(/m ago|h ago|just now/);
|
||||
expect(result).toBe(new Date(twoDaysAgo).toLocaleDateString());
|
||||
});
|
||||
|
||||
it("handles the boundary between minute and hour correctly", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const exactlyOneHourAgo = new Date(now - 3_600_000).toISOString();
|
||||
expect(formatAuditRelativeTime(exactlyOneHourAgo, now)).toBe("1h ago");
|
||||
});
|
||||
|
||||
it("handles the boundary between hour and day correctly", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
// 23h ago is < 24h so it shows "23h ago"; exactly 24h falls through to date string
|
||||
const twentyThreeHoursAgo = new Date(now - 23 * 3_600_000).toISOString();
|
||||
expect(formatAuditRelativeTime(twentyThreeHoursAgo, now)).toBe("23h ago");
|
||||
});
|
||||
|
||||
it("returns locale date string for exactly 24h ago (boundary)", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const exactlyOneDayAgo = new Date(now - 86_400_000).toISOString();
|
||||
const result = formatAuditRelativeTime(exactlyOneDayAgo, now);
|
||||
// diff is exactly 86_400_000, which is NOT < 86_400_000, so it falls through
|
||||
expect(result).toBe(new Date(exactlyOneDayAgo).toLocaleDateString());
|
||||
});
|
||||
|
||||
it("future timestamps return 'just now' (negative diff < 60_000)", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const future = new Date(now + 60_000).toISOString();
|
||||
// Negative diff passes diff < 60_000, returning "just now"
|
||||
expect(formatAuditRelativeTime(future, now)).toBe("just now");
|
||||
});
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Unit tests for pure helpers from MemoryInspectorPanel:
|
||||
* isPluginUnavailableError, formatRelativeTime, formatTTL
|
||||
*
|
||||
* These are the three exported non-component functions. The component
|
||||
* itself (MemoryInspectorPanel) requires full API + store mocking and
|
||||
* is exercised by the existing MemoryTab.test.tsx.
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { isPluginUnavailableError, formatTTL } from "../MemoryInspectorPanel";
|
||||
|
||||
// formatRelativeTime is not exported — tested via the component in MemoryTab.test.tsx
|
||||
|
||||
describe("isPluginUnavailableError", () => {
|
||||
it("returns true when Error message contains MEMORY_PLUGIN_URL", () => {
|
||||
const err = new Error("memory: could not resolve MEMORY_PLUGIN_URL — plugin not configured");
|
||||
expect(isPluginUnavailableError(err)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for Error containing MEMORY_PLUGIN_URL", () => {
|
||||
expect(isPluginUnavailableError(new Error("MEMORY_PLUGIN_URL is not set"))).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false for unrelated error messages", () => {
|
||||
expect(isPluginUnavailableError(new Error("workspace not found"))).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for null", () => {
|
||||
expect(isPluginUnavailableError(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for undefined", () => {
|
||||
expect(isPluginUnavailableError(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for plain objects without message", () => {
|
||||
expect(isPluginUnavailableError({ code: 503 })).toBe(false);
|
||||
});
|
||||
|
||||
it("is case-sensitive (MEMORY_PLUGIN_URL must match exactly)", () => {
|
||||
const lowerErr = new Error("memory_plugin_url missing");
|
||||
const upperErr = new Error("MEMORY_PLUGIN_URL missing");
|
||||
expect(isPluginUnavailableError(lowerErr)).toBe(false);
|
||||
expect(isPluginUnavailableError(upperErr)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatTTL", () => {
|
||||
it("returns '' for null", () => {
|
||||
expect(formatTTL(null)).toBe("");
|
||||
});
|
||||
|
||||
it("returns '' for undefined", () => {
|
||||
expect(formatTTL(undefined)).toBe("");
|
||||
});
|
||||
|
||||
it('returns "expired" when expiresAt is in the past', () => {
|
||||
const past = new Date(Date.now() - 60_000).toISOString();
|
||||
expect(formatTTL(past)).toBe("expired");
|
||||
});
|
||||
|
||||
it('returns "Xs" for less than a minute', () => {
|
||||
const soon = new Date(Date.now() + 30_000).toISOString();
|
||||
expect(formatTTL(soon)).toBe("30s");
|
||||
});
|
||||
|
||||
it('returns "Xm" for less than an hour', () => {
|
||||
const soon = new Date(Date.now() + 5 * 60_000).toISOString();
|
||||
expect(formatTTL(soon)).toBe("5m");
|
||||
});
|
||||
|
||||
it('returns "Xh" for less than a day', () => {
|
||||
const soon = new Date(Date.now() + 3 * 3_600_000).toISOString();
|
||||
expect(formatTTL(soon)).toBe("3h");
|
||||
});
|
||||
|
||||
it('returns "Xd" for more than a day', () => {
|
||||
const soon = new Date(Date.now() + 2 * 86_400_000).toISOString();
|
||||
expect(formatTTL(soon)).toBe("2d");
|
||||
});
|
||||
|
||||
it("returns '' for invalid date string", () => {
|
||||
expect(formatTTL("not-a-date")).toBe("");
|
||||
});
|
||||
|
||||
it("returns '' for empty string", () => {
|
||||
expect(formatTTL("")).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -1,390 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for SidePanel — general rendering and non-tab behaviors.
|
||||
*
|
||||
* Companion to SidePanel.tabs.test.tsx which covers tablist ARIA
|
||||
* and localStorage width persistence.
|
||||
*
|
||||
* Covers:
|
||||
* - Null when no node is selected
|
||||
* - Null when selectedNodeId points to a missing node
|
||||
* - Header: node name, role, tier badge
|
||||
* - MetaPill capability summary pills
|
||||
* - Resize handle: role=separator, aria-valuenow/min/max, aria-orientation
|
||||
* - Resize handle: ArrowLeft/Right/Home/End keyboard nav
|
||||
* - Needs-restart banner + Restart Now button
|
||||
* - Current-task banner with pulsing dot
|
||||
* - Footer shows workspace ID
|
||||
* - Close button calls selectNode(null)
|
||||
* - Tab switch via onClick fires setPanelTab
|
||||
* - setSidePanelWidth called on mount
|
||||
*/
|
||||
import React from "react";
|
||||
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SidePanel } from "../SidePanel";
|
||||
|
||||
// ── Tab content stubs ───────────────────────────────────────────────────────
|
||||
vi.mock("../tabs/DetailsTab", () => ({ DetailsTab: () => null }));
|
||||
vi.mock("../tabs/SkillsTab", () => ({ SkillsTab: () => null }));
|
||||
vi.mock("../tabs/ChatTab", () => ({ ChatTab: () => null }));
|
||||
vi.mock("../tabs/ConfigTab", () => ({ ConfigTab: () => null }));
|
||||
vi.mock("../tabs/TerminalTab", () => ({ TerminalTab: () => null }));
|
||||
vi.mock("../tabs/FilesTab", () => ({ FilesTab: () => null }));
|
||||
vi.mock("../MemoryInspectorPanel", () => ({ MemoryInspectorPanel: () => null }));
|
||||
vi.mock("../tabs/TracesTab", () => ({ TracesTab: () => null }));
|
||||
vi.mock("../tabs/EventsTab", () => ({ EventsTab: () => null }));
|
||||
vi.mock("../tabs/ActivityTab", () => ({ ActivityTab: () => null }));
|
||||
vi.mock("../tabs/ScheduleTab", () => ({ ScheduleTab: () => null }));
|
||||
vi.mock("../tabs/ChannelsTab", () => ({ ChannelsTab: () => null }));
|
||||
vi.mock("../AuditTrailPanel", () => ({ AuditTrailPanel: () => null }));
|
||||
vi.mock("../StatusDot", () => ({ StatusDot: () => null }));
|
||||
vi.mock("../Tooltip", () => ({
|
||||
Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
}));
|
||||
vi.mock("@/components/Toaster", () => ({ showToast: vi.fn() }));
|
||||
|
||||
// ── Canvas store mock — mutable so each test can reconfigure ───────────────
|
||||
const mockSetPanelTab = vi.fn();
|
||||
const mockSelectNode = vi.fn();
|
||||
const mockSetSidePanelWidth = vi.fn();
|
||||
const mockRestartWorkspace = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
const BASE_NODE = {
|
||||
id: "ws-1",
|
||||
data: {
|
||||
name: "Test Workspace",
|
||||
status: "online" as const,
|
||||
tier: 2,
|
||||
role: "Engineer",
|
||||
parentId: null,
|
||||
needsRestart: false,
|
||||
currentTask: null,
|
||||
agentCard: null,
|
||||
},
|
||||
};
|
||||
|
||||
// Mutable store state — tests reassign fields to test different states
|
||||
let storeState = {
|
||||
selectedNodeId: "ws-1" as string | null,
|
||||
panelTab: "chat",
|
||||
setPanelTab: mockSetPanelTab,
|
||||
selectNode: mockSelectNode,
|
||||
setSidePanelWidth: mockSetSidePanelWidth,
|
||||
nodes: [BASE_NODE],
|
||||
restartWorkspace: mockRestartWorkspace,
|
||||
};
|
||||
|
||||
vi.mock("@/store/canvas", () => ({
|
||||
useCanvasStore: Object.assign(
|
||||
vi.fn((selector: (s: typeof storeState) => unknown) => selector(storeState)),
|
||||
{ getState: () => storeState }
|
||||
),
|
||||
summarizeWorkspaceCapabilities: () => ({ runtime: "claude-code", skillCount: 3 }),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
mockSetPanelTab.mockReset();
|
||||
mockSelectNode.mockReset();
|
||||
mockSetSidePanelWidth.mockReset();
|
||||
mockRestartWorkspace.mockReset().mockResolvedValue(undefined);
|
||||
localStorage.clear();
|
||||
// Reset store state to default
|
||||
storeState = {
|
||||
selectedNodeId: "ws-1",
|
||||
panelTab: "chat",
|
||||
setPanelTab: mockSetPanelTab,
|
||||
selectNode: mockSelectNode,
|
||||
setSidePanelWidth: mockSetSidePanelWidth,
|
||||
nodes: [BASE_NODE],
|
||||
restartWorkspace: mockRestartWorkspace,
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
// ─── Null guard ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — null guard", () => {
|
||||
it("returns null when selectedNodeId is null", () => {
|
||||
storeState.selectedNodeId = null;
|
||||
const { container } = render(<SidePanel />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when selectedNodeId does not match any node", () => {
|
||||
storeState.selectedNodeId = "nonexistent-ws";
|
||||
storeState.nodes = [];
|
||||
const { container } = render(<SidePanel />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Header ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — header", () => {
|
||||
it("shows node name in heading", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByRole("heading", { name: "Test Workspace" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows node role", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByText("Engineer")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows tier badge with correct value", () => {
|
||||
render(<SidePanel />);
|
||||
// T2 appears in header badge AND meta pill — confirm at least one
|
||||
const all = screen.getAllByText("T2");
|
||||
expect(all.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("close button is present with aria-label", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByRole("button", { name: /close workspace panel/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("close button calls selectNode(null)", () => {
|
||||
render(<SidePanel />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /close workspace panel/i }));
|
||||
expect(mockSelectNode).toHaveBeenCalledWith(null);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── MetaPills ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — meta pills", () => {
|
||||
it("renders Tier, Runtime, Skills, and Status pills in the meta row", () => {
|
||||
render(<SidePanel />);
|
||||
// All four labels appear somewhere in the meta pills row
|
||||
expect(screen.getByText(/tier/i)).toBeTruthy();
|
||||
expect(screen.getByText(/runtime/i)).toBeTruthy();
|
||||
expect(screen.getByText(/skills/i)).toBeTruthy();
|
||||
expect(screen.getByText(/status/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows correct runtime value in meta pill", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByText("claude-code")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows skill count in meta pill", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByText("3")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Resize handle ──────────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — resize handle", () => {
|
||||
it("has role=separator", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByRole("separator")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("has aria-label='Resize workspace panel'", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByRole("separator").getAttribute("aria-label")).toBe(
|
||||
"Resize workspace panel"
|
||||
);
|
||||
});
|
||||
|
||||
it("has aria-valuenow=480 (default width)", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByRole("separator").getAttribute("aria-valuenow")).toBe("480");
|
||||
});
|
||||
|
||||
it("has aria-valuemin=320", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByRole("separator").getAttribute("aria-valuemin")).toBe("320");
|
||||
});
|
||||
|
||||
it("has aria-valuemax=800", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByRole("separator").getAttribute("aria-valuemax")).toBe("800");
|
||||
});
|
||||
|
||||
it("has aria-orientation=vertical", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByRole("separator").getAttribute("aria-orientation")).toBe("vertical");
|
||||
});
|
||||
|
||||
it("has tabIndex=0 (focusable)", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByRole("separator").getAttribute("tabindex")).toBe("0");
|
||||
});
|
||||
|
||||
it("ArrowLeft increases width by 16px (STEP — moves left edge rightward, widens panel)", () => {
|
||||
render(<SidePanel />);
|
||||
const sep = screen.getByRole("separator");
|
||||
fireEvent.keyDown(sep, { key: "ArrowLeft" });
|
||||
const panel = document.querySelector(".fixed") as HTMLElement;
|
||||
expect(parseInt(panel.style.width, 10)).toBe(480 + 16); // widens
|
||||
});
|
||||
|
||||
it("ArrowRight decreases width by 16px (STEP — moves left edge leftward, narrows panel)", () => {
|
||||
render(<SidePanel />);
|
||||
const sep = screen.getByRole("separator");
|
||||
fireEvent.keyDown(sep, { key: "ArrowRight" });
|
||||
const panel = document.querySelector(".fixed") as HTMLElement;
|
||||
expect(parseInt(panel.style.width, 10)).toBe(480 - 16); // narrows
|
||||
});
|
||||
|
||||
it("Home key sets width to MIN (320)", () => {
|
||||
render(<SidePanel />);
|
||||
fireEvent.keyDown(screen.getByRole("separator"), { key: "Home" });
|
||||
const panel = document.querySelector(".fixed") as HTMLElement;
|
||||
expect(parseInt(panel.style.width, 10)).toBe(320);
|
||||
});
|
||||
|
||||
it("End key sets width to MAX (800)", () => {
|
||||
render(<SidePanel />);
|
||||
fireEvent.keyDown(screen.getByRole("separator"), { key: "End" });
|
||||
const panel = document.querySelector(".fixed") as HTMLElement;
|
||||
expect(parseInt(panel.style.width, 10)).toBe(800);
|
||||
});
|
||||
|
||||
it("ArrowLeft persists new width to localStorage", () => {
|
||||
render(<SidePanel />);
|
||||
fireEvent.keyDown(screen.getByRole("separator"), { key: "ArrowLeft" });
|
||||
expect(localStorage.getItem("molecule:sidepanel-width")).toBe(String(480 + 16));
|
||||
});
|
||||
|
||||
it("Home persists new width to localStorage", () => {
|
||||
render(<SidePanel />);
|
||||
fireEvent.keyDown(screen.getByRole("separator"), { key: "Home" });
|
||||
expect(localStorage.getItem("molecule:sidepanel-width")).toBe("320");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Needs-restart banner ────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — needs-restart banner", () => {
|
||||
it("shows banner when needsRestart=true and no currentTask", () => {
|
||||
storeState.nodes = [{ ...BASE_NODE, data: { ...BASE_NODE.data, needsRestart: true, currentTask: null } }];
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByText(/config changed/i)).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /restart now/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does NOT show banner when needsRestart=false", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.queryByText(/config changed/i)).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: /restart now/i })).toBeNull();
|
||||
});
|
||||
|
||||
it("Restart Now button calls restartWorkspace(selectedNodeId)", () => {
|
||||
storeState.nodes = [{ ...BASE_NODE, data: { ...BASE_NODE.data, needsRestart: true, currentTask: null } }];
|
||||
render(<SidePanel />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /restart now/i }));
|
||||
expect(mockRestartWorkspace).toHaveBeenCalledWith("ws-1");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Current-task banner ────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — current-task banner", () => {
|
||||
it("shows banner when currentTask is set", () => {
|
||||
storeState.nodes = [{ ...BASE_NODE, data: { ...BASE_NODE.data, currentTask: "Deploying bundle..." } }];
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByText("Deploying bundle...")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does NOT show banner when currentTask is null", () => {
|
||||
render(<SidePanel />);
|
||||
expect(screen.queryByText(/deploying bundle/i)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Footer ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — footer", () => {
|
||||
it("footer shows workspace ID in monospace font", () => {
|
||||
render(<SidePanel />);
|
||||
// ws-1 appears in the footer with font-mono class
|
||||
expect(screen.getByText("ws-1")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tab switching ─────────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — tab switching", () => {
|
||||
it("clicking Details tab calls setPanelTab('details')", () => {
|
||||
render(<SidePanel />);
|
||||
fireEvent.click(screen.getByRole("tab", { name: /details/i }));
|
||||
expect(mockSetPanelTab).toHaveBeenCalledWith("details");
|
||||
});
|
||||
|
||||
it("clicking Plugins tab calls setPanelTab('skills')", () => {
|
||||
render(<SidePanel />);
|
||||
fireEvent.click(screen.getByRole("tab", { name: /plugins/i }));
|
||||
expect(mockSetPanelTab).toHaveBeenCalledWith("skills");
|
||||
});
|
||||
|
||||
it("clicking Terminal tab calls setPanelTab('terminal')", () => {
|
||||
render(<SidePanel />);
|
||||
fireEvent.click(screen.getByRole("tab", { name: /terminal/i }));
|
||||
expect(mockSetPanelTab).toHaveBeenCalledWith("terminal");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── setSidePanelWidth ─────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — setSidePanelWidth side-effect", () => {
|
||||
it("calls setSidePanelWidth with 480 (default width) on mount", () => {
|
||||
render(<SidePanel />);
|
||||
expect(mockSetSidePanelWidth).toHaveBeenCalledWith(480);
|
||||
});
|
||||
|
||||
it("updates setSidePanelWidth after keyboard resize", () => {
|
||||
render(<SidePanel />);
|
||||
mockSetSidePanelWidth.mockClear();
|
||||
fireEvent.keyDown(screen.getByRole("separator"), { key: "ArrowLeft" });
|
||||
expect(mockSetSidePanelWidth).toHaveBeenCalledWith(480 + 16);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Width localStorage ────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — width localStorage", () => {
|
||||
it("does not persist default width to localStorage on initial mount (only on user resize)", () => {
|
||||
render(<SidePanel />);
|
||||
// localStorage is only written by the keyboard resize handler, not on mount
|
||||
expect(localStorage.getItem("molecule:sidepanel-width")).toBeNull();
|
||||
});
|
||||
|
||||
it("reads saved width from localStorage", () => {
|
||||
localStorage.setItem("molecule:sidepanel-width", "600");
|
||||
const { container } = render(<SidePanel />);
|
||||
const panel = container.firstChild as HTMLElement;
|
||||
expect(panel.style.width).toBe("600px");
|
||||
});
|
||||
|
||||
it("caps saved width to default when below minimum", () => {
|
||||
localStorage.setItem("molecule:sidepanel-width", "100");
|
||||
const { container } = render(<SidePanel />);
|
||||
const panel = container.firstChild as HTMLElement;
|
||||
expect(panel.style.width).toBe("480px");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Offline status ─────────────────────────────────────────────────────────
|
||||
|
||||
describe("SidePanel — offline status", () => {
|
||||
it("shows tier badge even when node is offline", () => {
|
||||
storeState.nodes = [{ ...BASE_NODE, data: { ...BASE_NODE.data, status: "offline" as const } }];
|
||||
render(<SidePanel />);
|
||||
// T2 appears in both header badge and meta pill — just confirm at least one exists
|
||||
const all = screen.getAllByText("T2");
|
||||
expect(all.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("shows 'offline' in the Status meta pill when node is offline", () => {
|
||||
storeState.nodes = [{ ...BASE_NODE, data: { ...BASE_NODE.data, status: "offline" as const } }];
|
||||
render(<SidePanel />);
|
||||
expect(screen.getByText("offline")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,260 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for TemplatePalette — the floating sidebar drawer.
|
||||
*
|
||||
* Covers:
|
||||
* - Toggle button aria-label (open / closed)
|
||||
* - Sidebar renders when open, hides when closed
|
||||
* - Sidebar header: "Templates" heading, subtitle
|
||||
* - Loading state
|
||||
* - Empty state ("No templates found")
|
||||
* - Template cards: name, description, tier badge, skill pills
|
||||
* - Deploy button calls deploy()
|
||||
* - Errors swallowed → empty state shown
|
||||
* - setTemplatePaletteOpen called on open/close
|
||||
* - OrgTemplatesSection rendered inside sidebar
|
||||
* - Import Agent Folder button in footer
|
||||
* - Refresh templates button in footer
|
||||
*/
|
||||
import React from "react";
|
||||
import { render, screen, fireEvent, cleanup, act, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// ── Hoisted mocks — vi.hoisted() so they're available when vi.mock runs ──────
|
||||
// IMPORTANT: use plain vi.fn() in the return object (NOT `const fn = vi.fn(); return { fn }`)
|
||||
const { mockDeploy, mockSetTemplatePaletteOpen, mockGet } = vi.hoisted(() => ({
|
||||
mockDeploy: vi.fn(),
|
||||
mockSetTemplatePaletteOpen: vi.fn(),
|
||||
mockGet: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/useTemplateDeploy", () => ({
|
||||
useTemplateDeploy: () => ({
|
||||
deploy: mockDeploy,
|
||||
deploying: null,
|
||||
error: null,
|
||||
modal: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/store/canvas", () => ({
|
||||
useCanvasStore: vi.fn((selector: (s: { setTemplatePaletteOpen: typeof mockSetTemplatePaletteOpen }) => unknown) =>
|
||||
selector({ setTemplatePaletteOpen: mockSetTemplatePaletteOpen })
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api", () => ({
|
||||
api: { get: mockGet },
|
||||
}));
|
||||
|
||||
vi.mock("../OrgImportPreflightModal", () => ({
|
||||
OrgImportPreflightModal: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("../ConfirmDialog", () => ({
|
||||
ConfirmDialog: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("../Spinner", () => ({
|
||||
Spinner: () => <span data-testid="spinner" aria-hidden="true" />,
|
||||
}));
|
||||
|
||||
vi.mock("../Toaster", () => ({ showToast: vi.fn() }));
|
||||
|
||||
// ── Component import — after all mocks ──────────────────────────────────────
|
||||
import { TemplatePalette } from "../TemplatePalette";
|
||||
|
||||
beforeEach(() => {
|
||||
mockDeploy.mockReset();
|
||||
mockSetTemplatePaletteOpen.mockReset();
|
||||
mockGet.mockReset().mockResolvedValue([]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
async function flush() {
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
}
|
||||
|
||||
const MOCK_TEMPLATES = [
|
||||
{
|
||||
id: "tmpl-1",
|
||||
name: "Software Engineer",
|
||||
description: "Best for writing code",
|
||||
tier: 1,
|
||||
skills: ["web-search", "read-file", "write-file"],
|
||||
},
|
||||
{
|
||||
id: "tmpl-2",
|
||||
name: "Researcher",
|
||||
description: "Deep research agent",
|
||||
tier: 2,
|
||||
skills: [],
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Toggle button ─────────────────────────────────────────────────────────
|
||||
|
||||
describe("TemplatePalette — toggle button", () => {
|
||||
it("has aria-label='Open template palette' when closed", () => {
|
||||
render(<TemplatePalette />);
|
||||
expect(screen.getByRole("button", { name: /open template palette/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("has aria-label='Close template palette' when open", async () => {
|
||||
render(<TemplatePalette />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /open template palette/i }));
|
||||
await flush();
|
||||
expect(screen.getByRole("button", { name: /close template palette/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("clicking toggle opens sidebar", async () => {
|
||||
render(<TemplatePalette />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /open template palette/i }));
|
||||
await flush();
|
||||
expect(screen.getByRole("heading", { name: "Templates" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("clicking toggle again closes sidebar", async () => {
|
||||
render(<TemplatePalette />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /open template palette/i }));
|
||||
await flush();
|
||||
fireEvent.click(screen.getByRole("button", { name: /close template palette/i }));
|
||||
await flush();
|
||||
expect(screen.queryByRole("heading", { name: "Templates" })).toBeNull();
|
||||
});
|
||||
|
||||
it("calls setTemplatePaletteOpen(true) when opened", async () => {
|
||||
render(<TemplatePalette />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /open template palette/i }));
|
||||
await flush();
|
||||
expect(mockSetTemplatePaletteOpen).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it("calls setTemplatePaletteOpen(false) when closed", async () => {
|
||||
render(<TemplatePalette />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /open template palette/i }));
|
||||
await flush();
|
||||
mockSetTemplatePaletteOpen.mockClear();
|
||||
fireEvent.click(screen.getByRole("button", { name: /close template palette/i }));
|
||||
await flush();
|
||||
expect(mockSetTemplatePaletteOpen).toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Sidebar content ───────────────────────────────────────────────────────
|
||||
|
||||
describe("TemplatePalette — sidebar", () => {
|
||||
async function openSidebar() {
|
||||
fireEvent.click(screen.getByRole("button", { name: /open template palette/i }));
|
||||
await flush();
|
||||
}
|
||||
|
||||
it("shows 'Templates' heading", async () => {
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(screen.getByRole("heading", { name: "Templates" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows subtitle 'Click to deploy a workspace'", async () => {
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(screen.getByText(/click to deploy a workspace/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows loading state", async () => {
|
||||
mockGet.mockReturnValue(new Promise(() => {}));
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(screen.getByTestId("spinner")).toBeTruthy();
|
||||
expect(screen.getByText(/loading/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows empty state when no templates", async () => {
|
||||
mockGet.mockResolvedValue([]);
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(screen.getByText(/no templates found/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders template cards", async () => {
|
||||
mockGet.mockResolvedValue(MOCK_TEMPLATES);
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(screen.getByText("Software Engineer")).toBeTruthy();
|
||||
expect(screen.getByText("Researcher")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows template description", async () => {
|
||||
mockGet.mockResolvedValue(MOCK_TEMPLATES);
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(screen.getByText(/best for writing code/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows tier badge on template card", async () => {
|
||||
mockGet.mockResolvedValue(MOCK_TEMPLATES);
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
// T1 appears in tier badge
|
||||
expect(screen.getAllByText("T1").length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("shows up to 3 skill pills", async () => {
|
||||
mockGet.mockResolvedValue(MOCK_TEMPLATES);
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(screen.getByText("web-search")).toBeTruthy();
|
||||
expect(screen.getByText("read-file")).toBeTruthy();
|
||||
expect(screen.getByText("write-file")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows '+N more' when more than 3 skills", async () => {
|
||||
mockGet.mockResolvedValue([
|
||||
{ id: "tmpl-many", name: "Full Stack", description: "", tier: 1, skills: ["a", "b", "c", "d", "e"] },
|
||||
]);
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(screen.getByText("+2")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("deploy button calls deploy(t)", async () => {
|
||||
mockGet.mockResolvedValue(MOCK_TEMPLATES);
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
const deployBtns = screen.getAllByRole("button", { name: /software engineer/i });
|
||||
await act(async () => { deployBtns[0].click(); });
|
||||
expect(mockDeploy).toHaveBeenCalledWith(MOCK_TEMPLATES[0]);
|
||||
});
|
||||
|
||||
it("shows empty state when api.get rejects (error is swallowed)", async () => {
|
||||
mockGet.mockRejectedValue(new Error("server error"));
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/no templates found/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders OrgTemplatesSection inside sidebar", async () => {
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(document.querySelector("[data-testid='org-templates-section']")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders Import Agent Folder button in footer", async () => {
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(screen.getByRole("button", { name: /import agent folder/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders Refresh templates button in footer", async () => {
|
||||
render(<TemplatePalette />);
|
||||
await openSidebar();
|
||||
expect(screen.getByRole("button", { name: /^refresh templates$/i })).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,97 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* TopBar — canvas header scaffold with logo, canvas name, New Agent button,
|
||||
* and SettingsButton integration point.
|
||||
*
|
||||
* Coverage:
|
||||
* - Renders header with logo and canvas name (default and custom)
|
||||
* - New Agent button present and clickable
|
||||
* - SettingsButton rendered (via mock)
|
||||
* - Ref forwarding wired (settingsGearRef passed as ref prop)
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom — use DOM APIs.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import { TopBar } from "../TopBar";
|
||||
|
||||
vi.mock("@/components/settings/SettingsButton", () => ({
|
||||
SettingsButton: React.forwardRef<HTMLButtonElement, object>(
|
||||
(_props, ref) => <button ref={ref} aria-label="Settings" type="button">⚙</button>,
|
||||
),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
// ─── Render ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("TopBar — render", () => {
|
||||
it("renders the header element", () => {
|
||||
render(<TopBar />);
|
||||
const header = document.querySelector("header");
|
||||
expect(header).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows default canvas name 'Canvas'", () => {
|
||||
render(<TopBar />);
|
||||
expect(document.body.textContent).toContain("Canvas");
|
||||
});
|
||||
|
||||
it("shows custom canvas name when provided", () => {
|
||||
render(<TopBar canvasName="Production Canvas" />);
|
||||
expect(document.body.textContent).toContain("Production Canvas");
|
||||
expect(document.body.textContent).not.toContain("Canvas\n"); // not default
|
||||
});
|
||||
|
||||
it("renders New Agent button", () => {
|
||||
render(<TopBar />);
|
||||
const btn = Array.from(document.querySelectorAll("button")).find(
|
||||
(b) => b.textContent?.includes("New Agent"),
|
||||
);
|
||||
expect(btn).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders SettingsButton", () => {
|
||||
render(<TopBar />);
|
||||
const settingsBtn = document.querySelector('button[aria-label="Settings"]');
|
||||
expect(settingsBtn).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders logo icon", () => {
|
||||
render(<TopBar />);
|
||||
const logo = Array.from(document.querySelectorAll("span")).find(
|
||||
(s) => s.getAttribute("aria-hidden") === "true",
|
||||
);
|
||||
expect(logo).toBeTruthy();
|
||||
expect(logo?.textContent).toContain("☁");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Interaction ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe("TopBar — interaction", () => {
|
||||
it("New Agent button is in the DOM and not disabled", () => {
|
||||
render(<TopBar />);
|
||||
const btn = Array.from(document.querySelectorAll("button")).find(
|
||||
(b) => b.textContent?.includes("New Agent"),
|
||||
);
|
||||
expect(btn).toBeTruthy();
|
||||
expect(btn!.getAttribute("disabled")).toBeNull();
|
||||
});
|
||||
|
||||
it("renders without crashing with empty canvasName", () => {
|
||||
render(<TopBar canvasName="" />);
|
||||
expect(document.querySelector("header")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders without crashing with long canvasName", () => {
|
||||
const longName = "A".repeat(200);
|
||||
render(<TopBar canvasName={longName} />);
|
||||
expect(document.body.textContent).toContain(longName);
|
||||
});
|
||||
});
|
||||
@@ -1,323 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* MobileChat — mobile message thread + composer + sub-tabs.
|
||||
*
|
||||
* Per spec §04: wired to /workspaces/:id/a2a (method message/send).
|
||||
* Slimmer surface than desktop ChatTab: no attachments, no topology overlay.
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom — use DOM APIs.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import { MobileChat } from "../MobileChat";
|
||||
|
||||
// ─── Mock store ───────────────────────────────────────────────────────────────
|
||||
|
||||
const mockAgentId = "ws-chat-test";
|
||||
const mockOnBack = vi.fn();
|
||||
|
||||
// Module-level mutable state for the mock store.
|
||||
const mockStoreState = {
|
||||
nodes: [] as Array<{
|
||||
id: string;
|
||||
position: { x: number; y: number };
|
||||
data: Record<string, unknown>;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}>,
|
||||
agentMessages: {} as Record<string, Array<{ id: string; content: string; timestamp: string }>>,
|
||||
};
|
||||
|
||||
vi.mock("@/store/canvas", () => ({
|
||||
useCanvasStore: Object.assign(
|
||||
vi.fn((sel) => sel(mockStoreState)),
|
||||
{ getState: () => mockStoreState },
|
||||
),
|
||||
summarizeWorkspaceCapabilities: vi.fn((data: Record<string, unknown>) => {
|
||||
const agentCard = data.agentCard as Record<string, unknown> | null;
|
||||
const skills = Array.isArray(agentCard?.skills)
|
||||
? (agentCard.skills as Array<Record<string, unknown>>).map(
|
||||
(s) => String(s.name || s.id || ""),
|
||||
).filter(Boolean)
|
||||
: [];
|
||||
return {
|
||||
runtime: (typeof data.runtime === "string" && data.runtime)
|
||||
? data.runtime
|
||||
: (typeof agentCard?.runtime === "string" ? String(agentCard.runtime) : null),
|
||||
skills,
|
||||
skillCount: skills.length,
|
||||
currentTask: String(data.currentTask ?? ""),
|
||||
hasActiveTask: String(data.currentTask ?? "").trim().length > 0,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
// ─── Mock API ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const { mockApiPost } = vi.hoisted(() => ({
|
||||
mockApiPost: vi.fn().mockResolvedValue({ result: { parts: [] } }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api", () => ({
|
||||
api: { post: mockApiPost },
|
||||
}));
|
||||
|
||||
// ─── Fixtures ────────────────────────────────────────────────────────────────
|
||||
|
||||
const onlineNode = {
|
||||
id: mockAgentId,
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
name: "Chat Agent",
|
||||
status: "online",
|
||||
tier: 2,
|
||||
agentCard: {
|
||||
runtime: "claude-code",
|
||||
skills: [{ name: "web-search" }],
|
||||
},
|
||||
currentTask: "",
|
||||
activeTasks: 0,
|
||||
collapsed: false,
|
||||
role: "agent",
|
||||
lastErrorRate: 0,
|
||||
lastSampleError: "",
|
||||
url: "",
|
||||
parentId: null,
|
||||
runtime: "claude-code",
|
||||
needsRestart: false,
|
||||
},
|
||||
};
|
||||
|
||||
const offlineNode = {
|
||||
id: "ws-offline",
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
name: "Offline Agent",
|
||||
status: "offline",
|
||||
tier: 1,
|
||||
agentCard: null,
|
||||
currentTask: "",
|
||||
activeTasks: 0,
|
||||
collapsed: false,
|
||||
role: "agent",
|
||||
lastErrorRate: 0,
|
||||
lastSampleError: "",
|
||||
url: "",
|
||||
parentId: null,
|
||||
runtime: "claude-code",
|
||||
needsRestart: false,
|
||||
},
|
||||
};
|
||||
|
||||
const degradedNode = {
|
||||
id: "ws-degraded",
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
name: "Degraded Agent",
|
||||
status: "degraded",
|
||||
tier: 3,
|
||||
agentCard: null,
|
||||
currentTask: "",
|
||||
activeTasks: 0,
|
||||
collapsed: false,
|
||||
role: "agent",
|
||||
lastErrorRate: 0,
|
||||
lastSampleError: "",
|
||||
url: "",
|
||||
parentId: null,
|
||||
runtime: "claude-code",
|
||||
needsRestart: false,
|
||||
},
|
||||
};
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function renderChat(agentId: string, dark = false) {
|
||||
return render(
|
||||
<MobileChat
|
||||
agentId={agentId}
|
||||
dark={dark}
|
||||
onBack={mockOnBack}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Setup / teardown ─────────────────────────────────────────────────────────
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnBack.mockClear();
|
||||
mockStoreState.nodes = [];
|
||||
mockStoreState.agentMessages = {};
|
||||
mockApiPost.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
// ─── Not found ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileChat — agent not found", () => {
|
||||
it('renders "Agent not found." when node is absent', () => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
const { container } = renderChat("nonexistent-id");
|
||||
expect(container.textContent ?? "").toContain("Agent not found.");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Header ──────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileChat — header", () => {
|
||||
beforeEach(() => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
});
|
||||
|
||||
it("renders Back button with aria-label", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
const backBtn = container.querySelector('[aria-label="Back"]');
|
||||
expect(backBtn).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Back button calls onBack", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
const backBtn = container.querySelector('[aria-label="Back"]') as HTMLButtonElement;
|
||||
backBtn.click();
|
||||
expect(mockOnBack).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("renders agent name in header", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
expect(container.textContent ?? "").toContain("Chat Agent");
|
||||
});
|
||||
|
||||
it("renders a More button", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
const moreBtn = container.querySelector('[aria-label="More"]');
|
||||
expect(moreBtn).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders footer with agentId", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
expect(container.textContent ?? "").toContain(mockAgentId);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Composer ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileChat — composer", () => {
|
||||
beforeEach(() => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
});
|
||||
|
||||
it("renders a textarea for message input", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
const textarea = container.querySelector("textarea");
|
||||
expect(textarea).toBeTruthy();
|
||||
});
|
||||
|
||||
it("textarea has placeholder text", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
const textarea = container.querySelector("textarea") as HTMLTextAreaElement;
|
||||
expect(textarea.placeholder).toBeTruthy();
|
||||
expect(textarea.placeholder).toContain("Send a message");
|
||||
});
|
||||
|
||||
it("renders a Send button with aria-label", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
const sendBtn = container.querySelector('[aria-label="Send"]');
|
||||
expect(sendBtn).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Send button is disabled when textarea is empty (no draft)", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
const sendBtn = container.querySelector('[aria-label="Send"]') as HTMLButtonElement;
|
||||
expect(sendBtn.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tabs ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileChat — tabs", () => {
|
||||
beforeEach(() => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
});
|
||||
|
||||
it("renders My Chat and Agent Comms tab labels", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
const text = container.textContent ?? "";
|
||||
expect(text).toContain("My Chat");
|
||||
expect(text).toContain("Agent Comms");
|
||||
});
|
||||
|
||||
it("defaults to My Chat tab", () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
// My Chat is the default; if there are no messages it should show the empty state
|
||||
expect(container.textContent ?? "").toContain("My Chat");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Empty state ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileChat — empty state", () => {
|
||||
beforeEach(() => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
});
|
||||
|
||||
it('shows "Send a message to start chatting." when no messages', () => {
|
||||
const { container } = renderChat(mockAgentId);
|
||||
expect(container.textContent ?? "").toContain("Send a message to start chatting.");
|
||||
});
|
||||
|
||||
it("shows no messages when agentMessages[agentId] is absent (undefined)", () => {
|
||||
// Explicitly set to empty to simulate no stored messages
|
||||
mockStoreState.agentMessages = {};
|
||||
const { container } = renderChat(mockAgentId);
|
||||
expect(container.textContent ?? "").toContain("Send a message to start chatting.");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Agent status ────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileChat — agent status", () => {
|
||||
it("renders composer for online agent", () => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
const { container } = renderChat(mockAgentId);
|
||||
expect(container.querySelector("textarea")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders composer for offline agent (with status text)", () => {
|
||||
mockStoreState.nodes = [offlineNode];
|
||||
const { container } = renderChat("ws-offline");
|
||||
const textarea = container.querySelector("textarea") as HTMLTextAreaElement;
|
||||
// Offline agent: textarea should be disabled
|
||||
expect(textarea.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("renders composer for degraded agent", () => {
|
||||
mockStoreState.nodes = [degradedNode];
|
||||
const { container } = renderChat("ws-degraded");
|
||||
expect(container.querySelector("textarea")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("offline agent shows agent name", () => {
|
||||
mockStoreState.nodes = [offlineNode];
|
||||
const { container } = renderChat("ws-offline");
|
||||
expect(container.textContent ?? "").toContain("Offline Agent");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Dark mode ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileChat — dark mode", () => {
|
||||
beforeEach(() => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
});
|
||||
|
||||
it("renders without crashing in dark mode", () => {
|
||||
const { container } = renderChat(mockAgentId, true);
|
||||
expect(container.querySelector('[aria-label="Back"]')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,367 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* MobileDetail — agent detail page with tabbed content (Overview/Activity/Config/Memory).
|
||||
*
|
||||
* Per spec §03: tabbed agent detail page. MobileChat (MR !717) was also tested here.
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom — use DOM APIs.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import { MobileDetail } from "../MobileDetail";
|
||||
|
||||
// ─── Mock store ───────────────────────────────────────────────────────────────
|
||||
|
||||
const mockNodeId = "ws-detail-test";
|
||||
const mockOnBack = vi.fn();
|
||||
const mockOnChat = vi.fn();
|
||||
|
||||
// Module-level mutable state for the mock store.
|
||||
// Tests mutate this between cases to control what the component sees.
|
||||
const mockStoreState = {
|
||||
nodes: [] as Array<{
|
||||
id: string;
|
||||
position: { x: number; y: number };
|
||||
data: Record<string, unknown>;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}>,
|
||||
};
|
||||
|
||||
vi.mock("@/store/canvas", () => ({
|
||||
useCanvasStore: Object.assign(
|
||||
vi.fn((sel) => sel(mockStoreState)),
|
||||
{ getState: () => mockStoreState },
|
||||
),
|
||||
summarizeWorkspaceCapabilities: vi.fn((data: Record<string, unknown>) => {
|
||||
const agentCard = data.agentCard as Record<string, unknown> | null;
|
||||
const skills = Array.isArray(agentCard?.skills)
|
||||
? (agentCard.skills as Array<Record<string, unknown>>).map(
|
||||
(s) => String(s.name || s.id || ""),
|
||||
).filter(Boolean)
|
||||
: [];
|
||||
return {
|
||||
runtime: (typeof data.runtime === "string" && data.runtime)
|
||||
? data.runtime
|
||||
: (typeof agentCard?.runtime === "string" ? String(agentCard.runtime) : null),
|
||||
skills,
|
||||
skillCount: skills.length,
|
||||
currentTask: String(data.currentTask ?? ""),
|
||||
hasActiveTask: String(data.currentTask ?? "").trim().length > 0,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
// Stub the API so DetailActivity doesn't attempt real network calls.
|
||||
vi.mock("@/lib/api", () => ({ api: { get: vi.fn().mockResolvedValue([]) } }));
|
||||
|
||||
// ─── Fixtures ────────────────────────────────────────────────────────────────
|
||||
|
||||
const onlineNode = {
|
||||
id: mockNodeId,
|
||||
position: { x: 100, y: 200 },
|
||||
data: {
|
||||
name: "Test Agent",
|
||||
status: "online",
|
||||
tier: 2,
|
||||
agentCard: {
|
||||
runtime: "claude-code",
|
||||
skills: [
|
||||
{ name: "web-search", id: "skill-1" },
|
||||
{ name: "code-review", id: "skill-2" },
|
||||
{ name: "file-ops", id: "skill-3" },
|
||||
],
|
||||
},
|
||||
currentTask: "Reviewing PR #717",
|
||||
activeTasks: 3,
|
||||
collapsed: false,
|
||||
role: "agent",
|
||||
lastErrorRate: 0,
|
||||
lastSampleError: "",
|
||||
url: "",
|
||||
parentId: null,
|
||||
runtime: "claude-code",
|
||||
needsRestart: false,
|
||||
},
|
||||
width: 240,
|
||||
height: 130,
|
||||
};
|
||||
|
||||
const failedNode = {
|
||||
id: "ws-failed",
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
name: "Failed Worker",
|
||||
status: "failed",
|
||||
tier: 4,
|
||||
agentCard: null,
|
||||
currentTask: "",
|
||||
activeTasks: 0,
|
||||
collapsed: false,
|
||||
role: "agent",
|
||||
lastErrorRate: 0.8,
|
||||
lastSampleError: "Connection refused",
|
||||
url: "",
|
||||
parentId: null,
|
||||
runtime: "external",
|
||||
needsRestart: false,
|
||||
},
|
||||
};
|
||||
|
||||
const offlineNode = {
|
||||
id: "ws-offline",
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
name: "Offline Bot",
|
||||
status: "offline",
|
||||
tier: 1,
|
||||
agentCard: null,
|
||||
currentTask: "",
|
||||
activeTasks: 0,
|
||||
collapsed: false,
|
||||
role: "agent",
|
||||
lastErrorRate: 0,
|
||||
lastSampleError: "",
|
||||
url: "",
|
||||
parentId: null,
|
||||
runtime: "claude-code",
|
||||
needsRestart: false,
|
||||
},
|
||||
};
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function renderDetail(agentId: string, dark = false) {
|
||||
return render(
|
||||
<MobileDetail
|
||||
agentId={agentId}
|
||||
dark={dark}
|
||||
onBack={mockOnBack}
|
||||
onChat={mockOnChat}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Setup / teardown ─────────────────────────────────────────────────────────
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnBack.mockClear();
|
||||
mockOnChat.mockClear();
|
||||
mockStoreState.nodes = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
// ─── Not found ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileDetail — agent not found", () => {
|
||||
it('renders "Agent not found." when no node matches agentId', () => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
const { container } = renderDetail("nonexistent-id");
|
||||
expect(container.textContent ?? "").toContain("Agent not found.");
|
||||
});
|
||||
|
||||
it("does not render any tab buttons when agent not found", () => {
|
||||
mockStoreState.nodes = [];
|
||||
const { container } = renderDetail("ghost-agent");
|
||||
expect(container.querySelectorAll("button").length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Hero render ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileDetail — hero section", () => {
|
||||
beforeEach(() => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
});
|
||||
|
||||
it("renders the agent name as an h1", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
const h1 = container.querySelector("h1");
|
||||
expect(h1).toBeTruthy();
|
||||
expect(h1!.textContent).toBe("Test Agent");
|
||||
});
|
||||
|
||||
it("renders agent tag below the name", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
// Tag appears in the hero section, styled differently from the name
|
||||
expect(container.textContent ?? "").toContain("claude-code");
|
||||
});
|
||||
|
||||
it("renders a Back button with aria-label", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
const backBtn = container.querySelector('[aria-label="Back"]');
|
||||
expect(backBtn).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Back button calls onBack", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
const backBtn = container.querySelector('[aria-label="Back"]') as HTMLButtonElement;
|
||||
backBtn.click();
|
||||
expect(mockOnBack).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("renders a More button", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
const moreBtn = container.querySelector('[aria-label="More"]');
|
||||
expect(moreBtn).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders Chat CTA with icon text", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
expect(container.textContent ?? "").toContain("Open chat");
|
||||
});
|
||||
|
||||
it("Chat CTA calls onChat", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
const chatBtn = Array.from(container.querySelectorAll("button")).find(
|
||||
(b) => b.textContent?.includes("Open chat"),
|
||||
);
|
||||
expect(chatBtn).toBeTruthy();
|
||||
(chatBtn as HTMLButtonElement).click();
|
||||
expect(mockOnChat).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Pill stats ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileDetail — pill stats", () => {
|
||||
beforeEach(() => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
});
|
||||
|
||||
it("renders TIER pill with the agent tier", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
expect(container.textContent ?? "").toContain("TIER");
|
||||
});
|
||||
|
||||
it("renders RUNTIME pill", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
expect(container.textContent ?? "").toContain("RUNTIME");
|
||||
});
|
||||
|
||||
it("renders SKILLS pill with count", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
// 3 skills in the agentCard fixture
|
||||
expect(container.textContent ?? "").toContain("SKILLS");
|
||||
});
|
||||
|
||||
it("renders STATUS pill", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
expect(container.textContent ?? "").toContain("STATUS");
|
||||
});
|
||||
|
||||
it("STATUS pill shows agent status value", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
// online status from the fixture
|
||||
expect(container.textContent ?? "").toContain("online");
|
||||
});
|
||||
|
||||
it("renders all 4 pills for online agent", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
// Count the pill container divs — each PillStat is a div with specific inline styles
|
||||
// We verify by content: TIER, RUNTIME, SKILLS, STATUS should all be present
|
||||
const text = container.textContent ?? "";
|
||||
expect(text).toContain("TIER");
|
||||
expect(text).toContain("RUNTIME");
|
||||
expect(text).toContain("SKILLS");
|
||||
expect(text).toContain("STATUS");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tabs ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileDetail — tab switching", () => {
|
||||
beforeEach(() => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
});
|
||||
|
||||
it("renders all 4 tab buttons", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
const text = container.textContent ?? "";
|
||||
expect(text).toContain("Overview");
|
||||
expect(text).toContain("Activity");
|
||||
expect(text).toContain("Config");
|
||||
expect(text).toContain("Memory");
|
||||
});
|
||||
|
||||
it("defaults to Overview tab", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
// DetailOverview renders ID, Tier, Runtime, Active tasks, Skills, Origin rows
|
||||
expect(container.textContent ?? "").toContain("ID");
|
||||
expect(container.textContent ?? "").toContain("Tier");
|
||||
});
|
||||
|
||||
it("Overview tab shows agent ID", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
expect(container.textContent ?? "").toContain(mockNodeId);
|
||||
});
|
||||
|
||||
it("Overview tab shows active tasks count", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
// onlineNode has activeTasks: 3
|
||||
expect(container.textContent ?? "").toContain("Active tasks");
|
||||
expect(container.textContent ?? "").toContain("3");
|
||||
});
|
||||
|
||||
it("Overview tab shows skill count", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
// 3 skills in agentCard
|
||||
expect(container.textContent ?? "").toContain("Skills");
|
||||
expect(container.textContent ?? "").toContain("3 loaded");
|
||||
});
|
||||
|
||||
it("Config tab button is findable and is a button element", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
const configTab = Array.from(container.querySelectorAll("button")).find(
|
||||
(b) => b.textContent?.trim() === "Config",
|
||||
);
|
||||
expect(configTab).toBeTruthy();
|
||||
expect((configTab as HTMLButtonElement).type).toBe("button");
|
||||
});
|
||||
|
||||
it("Memory tab button is findable and is a button element", () => {
|
||||
const { container } = renderDetail(mockNodeId);
|
||||
const memoryTab = Array.from(container.querySelectorAll("button")).find(
|
||||
(b) => b.textContent?.trim() === "Memory",
|
||||
);
|
||||
expect(memoryTab).toBeTruthy();
|
||||
expect((memoryTab as HTMLButtonElement).type).toBe("button");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Status rendering ─────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileDetail — status rendering", () => {
|
||||
it("renders failed status for failed agent", () => {
|
||||
mockStoreState.nodes = [failedNode];
|
||||
const { container } = renderDetail("ws-failed");
|
||||
expect(container.textContent ?? "").toContain("Failed Worker");
|
||||
expect(container.textContent ?? "").toContain("failed");
|
||||
});
|
||||
|
||||
it("renders offline status for offline agent", () => {
|
||||
mockStoreState.nodes = [offlineNode];
|
||||
const { container } = renderDetail("ws-offline");
|
||||
expect(container.textContent ?? "").toContain("Offline Bot");
|
||||
expect(container.textContent ?? "").toContain("offline");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Dark mode ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileDetail — dark mode", () => {
|
||||
beforeEach(() => {
|
||||
mockStoreState.nodes = [onlineNode];
|
||||
});
|
||||
|
||||
it("renders without crashing in dark mode", () => {
|
||||
const { container } = renderDetail(mockNodeId, true);
|
||||
expect(container.querySelector("h1")?.textContent).toBe("Test Agent");
|
||||
});
|
||||
});
|
||||
@@ -1,245 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* MobileHome — workspace agent list + filter chips + spawn FAB.
|
||||
*
|
||||
* Per spec §01: live store data, filter by status, spawn FAB.
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom — use DOM APIs.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import { MobileHome } from "../MobileHome";
|
||||
|
||||
// ─── Mock store ───────────────────────────────────────────────────────────────
|
||||
|
||||
const mockOnOpen = vi.fn();
|
||||
const mockOnSpawn = vi.fn();
|
||||
|
||||
const mockStoreState = {
|
||||
nodes: [] as Array<{
|
||||
id: string;
|
||||
position: { x: number; y: number };
|
||||
data: Record<string, unknown>;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}>,
|
||||
};
|
||||
|
||||
vi.mock("@/store/canvas", () => ({
|
||||
useCanvasStore: Object.assign(
|
||||
vi.fn((sel) => sel(mockStoreState)),
|
||||
{ getState: () => mockStoreState },
|
||||
),
|
||||
summarizeWorkspaceCapabilities: vi.fn((data: Record<string, unknown>) => {
|
||||
const agentCard = data.agentCard as Record<string, unknown> | null;
|
||||
const skills = Array.isArray(agentCard?.skills)
|
||||
? (agentCard.skills as Array<Record<string, unknown>>).map(
|
||||
(s) => String(s.name || s.id || ""),
|
||||
).filter(Boolean)
|
||||
: [];
|
||||
return {
|
||||
runtime: (typeof data.runtime === "string" && data.runtime)
|
||||
? data.runtime
|
||||
: (typeof agentCard?.runtime === "string" ? String(agentCard.runtime) : null),
|
||||
skills,
|
||||
skillCount: skills.length,
|
||||
currentTask: String(data.currentTask ?? ""),
|
||||
hasActiveTask: String(data.currentTask ?? "").trim().length > 0,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
// ─── Fixtures ───────────────────────────────────────────────────────────────
|
||||
|
||||
function makeNode(overrides: Partial<Record<string, unknown>> = {}) {
|
||||
return {
|
||||
id: `ws-${Math.random().toString(36).slice(2, 7)}`,
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
name: "Agent",
|
||||
status: "online",
|
||||
tier: 2,
|
||||
agentCard: null,
|
||||
currentTask: "",
|
||||
activeTasks: 0,
|
||||
collapsed: false,
|
||||
role: "agent",
|
||||
lastErrorRate: 0,
|
||||
lastSampleError: "",
|
||||
url: "",
|
||||
parentId: null,
|
||||
runtime: "claude-code",
|
||||
needsRestart: false,
|
||||
...overrides,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const onlineAgent = makeNode({ name: "Online Agent", status: "online", tier: 2 });
|
||||
const failedAgent = makeNode({ name: "Failed Agent", status: "failed", tier: 4 });
|
||||
const pausedAgent = makeNode({ name: "Paused Agent", status: "paused", tier: 1 });
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function renderHome(overrides: Partial<{
|
||||
dark: boolean;
|
||||
density: "compact" | "regular";
|
||||
workspaceLabel: string;
|
||||
username: string;
|
||||
}> = {}) {
|
||||
return render(
|
||||
<MobileHome
|
||||
dark={overrides.dark ?? false}
|
||||
density={overrides.density ?? "regular"}
|
||||
onOpen={mockOnOpen}
|
||||
onSpawn={mockOnSpawn}
|
||||
workspaceLabel={overrides.workspaceLabel}
|
||||
username={overrides.username}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Setup / teardown ─────────────────────────────────────────────────────────
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnOpen.mockClear();
|
||||
mockOnSpawn.mockClear();
|
||||
mockStoreState.nodes = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
// ─── Structure ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileHome — page structure", () => {
|
||||
it('renders "Agents" heading', () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome();
|
||||
const h1 = container.querySelector("h1");
|
||||
expect(h1).toBeTruthy();
|
||||
expect(h1!.textContent).toBe("Agents");
|
||||
});
|
||||
|
||||
it("renders WorkspacePill with agent count", () => {
|
||||
mockStoreState.nodes = [onlineAgent, failedAgent];
|
||||
const { container } = renderHome();
|
||||
// WorkspacePill renders the agent count somewhere in the DOM
|
||||
expect(container.textContent ?? "").toContain("2");
|
||||
});
|
||||
|
||||
it('shows "live" suffix in subheading', () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome();
|
||||
// Single agent → "1 workspace · live" (singular)
|
||||
expect(container.textContent ?? "").toContain("workspace");
|
||||
expect(container.textContent ?? "").toContain("live");
|
||||
});
|
||||
|
||||
it("renders FilterChips row", () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome();
|
||||
// FilterChips renders buttons for "All", "Online", "Issues", "Paused"
|
||||
const text = container.textContent ?? "";
|
||||
expect(text).toContain("All");
|
||||
expect(text).toContain("Online");
|
||||
expect(text).toContain("Issues");
|
||||
});
|
||||
|
||||
it("renders Workspace section label", () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome();
|
||||
expect(container.textContent ?? "").toContain("Workspace");
|
||||
});
|
||||
|
||||
it("renders spawn FAB with aria-label", () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome();
|
||||
const fab = container.querySelector('[aria-label="Spawn new agent"]');
|
||||
expect(fab).toBeTruthy();
|
||||
});
|
||||
|
||||
it("FAB calls onSpawn", () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome();
|
||||
const fab = container.querySelector('[aria-label="Spawn new agent"]') as HTMLButtonElement;
|
||||
fab.click();
|
||||
expect(mockOnSpawn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("shows username when provided", () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome({ username: "alice@example.com" });
|
||||
expect(container.textContent ?? "").toContain("alice@example.com");
|
||||
});
|
||||
|
||||
it("omits username when not provided", () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome();
|
||||
expect(container.querySelector('[style*="letter-spacing"]')?.textContent).not.toContain("@");
|
||||
});
|
||||
|
||||
it("renders with custom workspaceLabel", () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome({ workspaceLabel: "Production" });
|
||||
expect(container.textContent ?? "").toContain("Production");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Agent list ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileHome — agent list", () => {
|
||||
it("renders agent cards when nodes are present", () => {
|
||||
mockStoreState.nodes = [onlineAgent, failedAgent, pausedAgent];
|
||||
const { container } = renderHome();
|
||||
expect(container.textContent ?? "").toContain("Online Agent");
|
||||
expect(container.textContent ?? "").toContain("Failed Agent");
|
||||
expect(container.textContent ?? "").toContain("Paused Agent");
|
||||
});
|
||||
|
||||
it("shows 'No agents match this filter.' when filter returns empty", () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome();
|
||||
// By default filter is "all" — all agents match
|
||||
expect(container.textContent ?? "").not.toContain("No agents match");
|
||||
// If we could set filter to something that filters everything out...
|
||||
// (filter is internal state, we test the "all" default)
|
||||
expect(container.querySelectorAll("button").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("renders no agents when node list is empty", () => {
|
||||
mockStoreState.nodes = [];
|
||||
const { container } = renderHome();
|
||||
// Should show "0 workspaces" and "No agents match this filter."
|
||||
expect(container.textContent ?? "").toContain("0 workspace");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Agent count display ──────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileHome — agent count", () => {
|
||||
it("shows singular 'workspace' when count is 1", () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome();
|
||||
expect(container.textContent ?? "").toContain("1 workspace");
|
||||
});
|
||||
|
||||
it("shows plural 'workspaces' when count is > 1", () => {
|
||||
mockStoreState.nodes = [onlineAgent, failedAgent];
|
||||
const { container } = renderHome();
|
||||
expect(container.textContent ?? "").toContain("2 workspaces");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Dark mode ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileHome — dark mode", () => {
|
||||
it("renders without crashing in dark mode", () => {
|
||||
mockStoreState.nodes = [onlineAgent];
|
||||
const { container } = renderHome({ dark: true });
|
||||
expect(container.querySelector("h1")?.textContent).toBe("Agents");
|
||||
});
|
||||
});
|
||||
@@ -1,212 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* MobileMe — theme, accent, and density preferences.
|
||||
*
|
||||
* Per spec: theme + accent + density settings for mobile.
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom — use DOM APIs.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import { MobileMe } from "../MobileMe";
|
||||
|
||||
// ─── Mock theme provider ───────────────────────────────────────────────────────
|
||||
|
||||
const mockSetTheme = vi.fn();
|
||||
const mockSetAccent = vi.fn();
|
||||
const mockSetDensity = vi.fn();
|
||||
|
||||
vi.mock("@/lib/theme-provider", () => ({
|
||||
useTheme: vi.fn(() => ({
|
||||
theme: "system",
|
||||
resolvedTheme: "light",
|
||||
setTheme: mockSetTheme,
|
||||
})),
|
||||
}));
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function renderMe(overrides: Partial<{
|
||||
dark: boolean;
|
||||
accent: string;
|
||||
density: "compact" | "regular";
|
||||
}> = {}) {
|
||||
return render(
|
||||
<MobileMe
|
||||
dark={overrides.dark ?? false}
|
||||
accent={overrides.accent ?? "#2f9e6a"}
|
||||
setAccent={mockSetAccent}
|
||||
density={overrides.density ?? "regular"}
|
||||
setDensity={mockSetDensity}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Setup / teardown ─────────────────────────────────────────────────────────
|
||||
|
||||
beforeEach(() => {
|
||||
mockSetTheme.mockClear();
|
||||
mockSetAccent.mockClear();
|
||||
mockSetDensity.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
// ─── Structure ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileMe — page structure", () => {
|
||||
it('renders "Me" heading', () => {
|
||||
const { container } = renderMe();
|
||||
const h1 = container.querySelector("h1");
|
||||
expect(h1).toBeTruthy();
|
||||
expect(h1!.textContent).toBe("Me");
|
||||
});
|
||||
|
||||
it("renders theme section label", () => {
|
||||
const { container } = renderMe();
|
||||
expect(container.textContent ?? "").toContain("Theme");
|
||||
});
|
||||
|
||||
it("renders theme options: System, Light, Dark", () => {
|
||||
const { container } = renderMe();
|
||||
const text = container.textContent ?? "";
|
||||
expect(text).toContain("System");
|
||||
expect(text).toContain("Light");
|
||||
expect(text).toContain("Dark");
|
||||
});
|
||||
|
||||
it("renders accent section label", () => {
|
||||
const { container } = renderMe();
|
||||
expect(container.textContent ?? "").toContain("Accent");
|
||||
});
|
||||
|
||||
it("renders all 5 accent color swatches", () => {
|
||||
const { container } = renderMe();
|
||||
const swatches = container.querySelectorAll("button[aria-label]");
|
||||
// 5 accent swatches + theme buttons + density buttons = more than 5
|
||||
// We verify the accent swatches by checking aria-labels
|
||||
const accentLabels = Array.from(swatches)
|
||||
.map((b) => b.getAttribute("aria-label") ?? "")
|
||||
.filter((l) => l.startsWith("Set accent"));
|
||||
expect(accentLabels.length).toBe(5);
|
||||
});
|
||||
|
||||
it("renders density section label", () => {
|
||||
const { container } = renderMe();
|
||||
expect(container.textContent ?? "").toContain("Density");
|
||||
});
|
||||
|
||||
it("renders density options: Regular, Compact", () => {
|
||||
const { container } = renderMe();
|
||||
const text = container.textContent ?? "";
|
||||
expect(text).toContain("Regular");
|
||||
expect(text).toContain("Compact");
|
||||
});
|
||||
|
||||
it("renders version footer", () => {
|
||||
const { container } = renderMe();
|
||||
expect(container.textContent ?? "").toContain("Mobile design preview");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Theme selection ──────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileMe — theme selection", () => {
|
||||
it("renders System as the active theme (from mock)", () => {
|
||||
const { container } = renderMe();
|
||||
// The theme buttons are rendered; System is active in our mock
|
||||
// We verify the buttons exist and are findable
|
||||
const buttons = Array.from(container.querySelectorAll("button"));
|
||||
const themeButtons = buttons.filter(
|
||||
(b) => ["System", "Light", "Dark"].includes(b.textContent?.trim() ?? ""),
|
||||
);
|
||||
expect(themeButtons.length).toBe(3);
|
||||
});
|
||||
|
||||
it("calls setTheme when a theme button is clicked", () => {
|
||||
const { container } = renderMe();
|
||||
const darkBtn = Array.from(container.querySelectorAll("button")).find(
|
||||
(b) => b.textContent?.trim() === "Dark",
|
||||
);
|
||||
expect(darkBtn).toBeTruthy();
|
||||
darkBtn!.click();
|
||||
expect(mockSetTheme).toHaveBeenCalledWith("dark");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Accent selection ────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileMe — accent selection", () => {
|
||||
it("renders accent buttons with aria-label", () => {
|
||||
const { container } = renderMe();
|
||||
const swatches = container.querySelectorAll("button[aria-label]");
|
||||
const accentSwatches = Array.from(swatches).filter(
|
||||
(b) => (b.getAttribute("aria-label") ?? "").startsWith("Set accent"),
|
||||
);
|
||||
expect(accentSwatches.length).toBe(5);
|
||||
});
|
||||
|
||||
it("calls setAccent with the correct color", () => {
|
||||
const { container } = renderMe();
|
||||
const swatch = Array.from(container.querySelectorAll("button[aria-label]")).find(
|
||||
(b) => b.getAttribute("aria-label") === "Set accent #3b6fe0",
|
||||
);
|
||||
expect(swatch).toBeTruthy();
|
||||
swatch!.click();
|
||||
expect(mockSetAccent).toHaveBeenCalledWith("#3b6fe0");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Density selection ────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileMe — density selection", () => {
|
||||
it("renders density buttons", () => {
|
||||
const { container } = renderMe();
|
||||
const buttons = Array.from(container.querySelectorAll("button"));
|
||||
const densityButtons = buttons.filter(
|
||||
(b) => ["Regular", "Compact"].includes(b.textContent?.trim() ?? ""),
|
||||
);
|
||||
expect(densityButtons.length).toBe(2);
|
||||
});
|
||||
|
||||
it("calls setDensity when Compact is clicked", () => {
|
||||
const { container } = renderMe({ density: "regular" });
|
||||
const compactBtn = Array.from(container.querySelectorAll("button")).find(
|
||||
(b) => b.textContent?.trim() === "Compact",
|
||||
);
|
||||
expect(compactBtn).toBeTruthy();
|
||||
compactBtn!.click();
|
||||
expect(mockSetDensity).toHaveBeenCalledWith("compact");
|
||||
});
|
||||
|
||||
it("calls setDensity when Regular is clicked", () => {
|
||||
const { container } = renderMe({ density: "compact" });
|
||||
const regularBtn = Array.from(container.querySelectorAll("button")).find(
|
||||
(b) => b.textContent?.trim() === "Regular",
|
||||
);
|
||||
expect(regularBtn).toBeTruthy();
|
||||
regularBtn!.click();
|
||||
expect(mockSetDensity).toHaveBeenCalledWith("regular");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Dark mode ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("MobileMe — dark mode", () => {
|
||||
it("renders without crashing in dark mode", () => {
|
||||
const { container } = renderMe({ dark: true });
|
||||
expect(container.querySelector("h1")?.textContent).toBe("Me");
|
||||
});
|
||||
|
||||
it("renders theme, accent, and density sections in dark mode", () => {
|
||||
const { container } = renderMe({ dark: true });
|
||||
const text = container.textContent ?? "";
|
||||
expect(text).toContain("Theme");
|
||||
expect(text).toContain("Accent");
|
||||
expect(text).toContain("Density");
|
||||
});
|
||||
});
|
||||
@@ -1,184 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* mobile/components.tsx — pure functions.
|
||||
*
|
||||
* Covers:
|
||||
* - toMobileAgent: full transform, all status/tier/runtime cases
|
||||
* - classifyForFilter: online → "online", failed/degraded → "issue",
|
||||
* starting/paused/offline → "paused"
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom — use DOM APIs.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Node } from "@xyflow/react";
|
||||
import type { WorkspaceNodeData } from "@/store/canvas";
|
||||
|
||||
import {
|
||||
AgentCard,
|
||||
FilterChips,
|
||||
RemoteBadge,
|
||||
classifyForFilter,
|
||||
toMobileAgent,
|
||||
type MobileAgent,
|
||||
type AgentFilter,
|
||||
} from "../components";
|
||||
|
||||
// ─── Mock store ────────────────────────────────────────────────────────────────
|
||||
|
||||
const mockSummarize = vi.fn();
|
||||
|
||||
vi.mock("@/store/canvas", () => ({
|
||||
summarizeWorkspaceCapabilities: (...args: unknown[]) => mockSummarize(...args),
|
||||
}));
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function makeNode(overrides: Partial<WorkspaceNodeData> = {}): Node<WorkspaceNodeData> {
|
||||
return {
|
||||
id: "ws-1",
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
name: "Test Agent",
|
||||
status: "online",
|
||||
tier: 2,
|
||||
agentCard: null,
|
||||
activeTasks: 0,
|
||||
collapsed: false,
|
||||
role: "assistant",
|
||||
lastErrorRate: 0,
|
||||
lastSampleError: "",
|
||||
url: "http://localhost:9000",
|
||||
parentId: null,
|
||||
runtime: "langgraph",
|
||||
currentTask: "",
|
||||
budgetLimit: null,
|
||||
...overrides,
|
||||
} as WorkspaceNodeData,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── toMobileAgent ────────────────────────────────────────────────────────────
|
||||
|
||||
describe("toMobileAgent — basic fields", () => {
|
||||
beforeEach(() => {
|
||||
mockSummarize.mockReturnValue({
|
||||
runtime: "langgraph",
|
||||
skills: [],
|
||||
skillCount: 0,
|
||||
currentTask: "",
|
||||
hasActiveTask: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("maps id and name", () => {
|
||||
const node = makeNode({ name: "My Agent" });
|
||||
const agent = toMobileAgent(node);
|
||||
expect(agent.id).toBe("ws-1");
|
||||
expect(agent.name).toBe("My Agent");
|
||||
});
|
||||
|
||||
it("uses id as name when name is empty", () => {
|
||||
const node = makeNode({ name: "" });
|
||||
const agent = toMobileAgent(node);
|
||||
expect(agent.name).toBe("ws-1");
|
||||
});
|
||||
|
||||
it("maps tier correctly for tier 1-4", () => {
|
||||
const tiers: Array<[number, MobileAgent["tier"]]> = [
|
||||
[1, "T1"],
|
||||
[2, "T2"],
|
||||
[3, "T3"],
|
||||
[4, "T4"],
|
||||
];
|
||||
for (const [tier, code] of tiers) {
|
||||
const agent = toMobileAgent(makeNode({ tier }));
|
||||
expect(agent.tier).toBe(code);
|
||||
}
|
||||
});
|
||||
|
||||
it("maps status to MobileStatus", () => {
|
||||
const statuses: Array<[string, MobileAgent["status"]]> = [
|
||||
["online", "online"],
|
||||
["starting", "starting"],
|
||||
["degraded", "degraded"],
|
||||
["failed", "failed"],
|
||||
["paused", "paused"],
|
||||
["offline", "offline"],
|
||||
];
|
||||
for (const [status, mobileStatus] of statuses) {
|
||||
const agent = toMobileAgent(makeNode({ status }));
|
||||
expect(agent.status).toBe(mobileStatus);
|
||||
}
|
||||
});
|
||||
|
||||
it("marks remote=true for external runtime", () => {
|
||||
mockSummarize.mockReturnValue({ runtime: "external", skills: [], skillCount: 0, currentTask: "", hasActiveTask: false });
|
||||
const agent = toMobileAgent(makeNode({ runtime: "external" }));
|
||||
expect(agent.remote).toBe(true);
|
||||
});
|
||||
|
||||
it("marks remote=false for non-external runtime", () => {
|
||||
mockSummarize.mockReturnValue({ runtime: "langgraph", skills: [], skillCount: 0, currentTask: "", hasActiveTask: false });
|
||||
const agent = toMobileAgent(makeNode({ runtime: "langgraph" }));
|
||||
expect(agent.remote).toBe(false);
|
||||
});
|
||||
|
||||
it("maps runtime from summarizeWorkspaceCapabilities", () => {
|
||||
mockSummarize.mockReturnValue({ runtime: "claude-code", skills: [], skillCount: 0, currentTask: "", hasActiveTask: false });
|
||||
const agent = toMobileAgent(makeNode({ runtime: "" }));
|
||||
expect(agent.runtime).toBe("claude-code");
|
||||
});
|
||||
|
||||
it("maps skills count from summarizeWorkspaceCapabilities", () => {
|
||||
mockSummarize.mockReturnValue({ runtime: "langgraph", skills: ["skill1", "skill2"], skillCount: 2, currentTask: "", hasActiveTask: false });
|
||||
const agent = toMobileAgent(makeNode());
|
||||
expect(agent.skills).toBe(2);
|
||||
});
|
||||
|
||||
it("maps activeTasks to calls", () => {
|
||||
const agent = toMobileAgent(makeNode({ activeTasks: 5 }));
|
||||
expect(agent.calls).toBe(5);
|
||||
});
|
||||
|
||||
it("defaults calls to 0 when activeTasks is not a number", () => {
|
||||
const node = makeNode() as Node<WorkspaceNodeData>;
|
||||
node.data.activeTasks = "not a number" as unknown as number;
|
||||
const agent = toMobileAgent(node);
|
||||
expect(agent.calls).toBe(0);
|
||||
});
|
||||
|
||||
it("maps role as desc fallback to currentTask", () => {
|
||||
mockSummarize.mockReturnValue({ runtime: "langgraph", skills: [], skillCount: 0, currentTask: "Doing analysis", hasActiveTask: true });
|
||||
const agent = toMobileAgent(makeNode({ role: "" }));
|
||||
expect(agent.desc).toBe("Doing analysis");
|
||||
});
|
||||
|
||||
it("uses role as desc when currentTask is empty", () => {
|
||||
mockSummarize.mockReturnValue({ runtime: "langgraph", skills: [], skillCount: 0, currentTask: "", hasActiveTask: false });
|
||||
const agent = toMobileAgent(makeNode({ role: "researcher" }));
|
||||
expect(agent.desc).toBe("researcher");
|
||||
});
|
||||
|
||||
it("maps parentId from node data", () => {
|
||||
const node = makeNode({ parentId: "ws-parent" });
|
||||
const agent = toMobileAgent(node);
|
||||
expect(agent.parentId).toBe("ws-parent");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── classifyForFilter ─────────────────────────────────────────────────────────
|
||||
|
||||
describe("classifyForFilter", () => {
|
||||
const cases: Array<[MobileAgent["status"], AgentFilter]> = [
|
||||
["online", "online"],
|
||||
["starting", "paused"],
|
||||
["degraded", "issue"],
|
||||
["failed", "issue"],
|
||||
["paused", "paused"],
|
||||
["offline", "paused"],
|
||||
];
|
||||
|
||||
it.each(cases)("normalizeStatus(%s) → %s", (status, expected) => {
|
||||
expect(classifyForFilter(status)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -1,340 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for AddKeyForm — inline form for adding a new API key.
|
||||
*
|
||||
* Covers:
|
||||
* - Header + key name + value fields rendered
|
||||
* - Key name auto-uppercased on input
|
||||
* - Validation: UPPER_SNAKE_CASE required, duplicate name blocked
|
||||
* - Provider hint shown for known providers (GitHub, Anthropic, OpenRouter)
|
||||
* - Provider hint hidden for custom key names
|
||||
* - Debounced value validation
|
||||
* - Save button disabled when form invalid / saving
|
||||
* - createSecret called on save with correct args
|
||||
* - onCancel called on Cancel click
|
||||
* - Save error shown on failure
|
||||
* - TestConnectionButton shown when value is format-valid and provider supports it
|
||||
*/
|
||||
import React from "react";
|
||||
import { render, screen, fireEvent, cleanup, act, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AddKeyForm } from "../AddKeyForm";
|
||||
|
||||
// ── Mocks ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
const { mockValidateSecretValue, mockIsValidKeyName, mockInferGroup } = vi.hoisted(() => ({
|
||||
mockValidateSecretValue: vi.fn((value: string) => {
|
||||
// Return error for "bad-value" to test ValidationHint display
|
||||
if (value === "bad-value") return "Invalid format";
|
||||
return null;
|
||||
}),
|
||||
mockIsValidKeyName: vi.fn((name: string) => /^[A-Z][A-Z0-9_]*$/.test(name)),
|
||||
mockInferGroup: vi.fn((name: string) => {
|
||||
const u = name.toUpperCase();
|
||||
if (u.includes("GITHUB")) return "github" as const;
|
||||
if (u.includes("ANTHROPIC")) return "anthropic" as const;
|
||||
if (u.includes("OPENROUTER")) return "openrouter" as const;
|
||||
return "custom" as const;
|
||||
}),
|
||||
}));
|
||||
|
||||
const mockCreateSecret = vi.fn();
|
||||
|
||||
vi.mock("@/stores/secrets-store", () => ({
|
||||
useSecretsStore: Object.assign(
|
||||
vi.fn((selector?: (s: { createSecret: typeof mockCreateSecret }) => unknown) =>
|
||||
selector ? selector({ createSecret: mockCreateSecret }) : { createSecret: mockCreateSecret }
|
||||
),
|
||||
{ getState: () => ({ createSecret: mockCreateSecret }) },
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/validation/secret-formats", () => ({
|
||||
validateSecretValue: mockValidateSecretValue,
|
||||
isValidKeyName: mockIsValidKeyName,
|
||||
inferGroup: mockInferGroup,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/services", () => ({
|
||||
SERVICES: {
|
||||
github: { label: "GitHub", icon: "github", keyNames: [], docsUrl: "https://github.com", testSupported: true },
|
||||
anthropic: { label: "Anthropic", icon: "anthropic", keyNames: [], docsUrl: "https://anthropic.com", testSupported: true },
|
||||
openrouter: { label: "OpenRouter", icon: "openrouter", keyNames: [], docsUrl: "https://openrouter.ai", testSupported: true },
|
||||
custom: { label: "Other", icon: "key", keyNames: [], docsUrl: "", testSupported: false },
|
||||
},
|
||||
KEY_NAME_SUGGESTIONS: [],
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/KeyValueField", () => ({
|
||||
KeyValueField: ({ value, onChange, disabled }: { value: string; onChange: (v: string) => void; disabled?: boolean }) => (
|
||||
<textarea
|
||||
data-testid="key-value-field"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
aria-label="Key value"
|
||||
/>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/ValidationHint", () => ({
|
||||
ValidationHint: ({ error }: { error: string | null }) =>
|
||||
error ? <span role="alert">{error}</span> : null,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/TestConnectionButton", () => ({
|
||||
TestConnectionButton: () => <button data-testid="test-connection-btn" type="button">Test connection</button>,
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateSecret.mockReset().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
async function typeKeyName(name: string) {
|
||||
const input = screen.getByLabelText("Key name");
|
||||
fireEvent.change(input, { target: { value: name } });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
}
|
||||
|
||||
async function typeValue(val: string) {
|
||||
const textarea = screen.getByTestId("key-value-field");
|
||||
fireEvent.change(textarea, { target: { value: val } });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
}
|
||||
|
||||
// ─── Initial render ─────────────────────────────────────────────────────────
|
||||
|
||||
describe("AddKeyForm — initial render", () => {
|
||||
it("renders header 'Add New Key'", () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
expect(screen.getByText("Add New Key")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("has key name and value inputs", () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
expect(screen.getByLabelText("Key name")).toBeTruthy();
|
||||
expect(screen.getByTestId("key-value-field")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Save and Cancel buttons present", () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
expect(screen.getByRole("button", { name: /save key/i })).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /cancel/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Save button disabled initially", () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
expect((screen.getByRole("button", { name: /save key/i }) as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Key name validation ────────────────────────────────────────────────────
|
||||
|
||||
describe("AddKeyForm — key name validation", () => {
|
||||
it("auto-uppercases key name input", async () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
const input = screen.getByLabelText("Key name") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "github_token" } });
|
||||
expect(input.value).toBe("GITHUB_TOKEN");
|
||||
});
|
||||
|
||||
it("shows error for key name starting with digit (invalid UPPER_SNAKE_CASE)", async () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
// The key name input auto-uppercases, so "123_token" → "123_TOKEN"
|
||||
// which fails /^[A-Z][A-Z0-9_]*$/ (must start with uppercase letter)
|
||||
const input = screen.getByLabelText("Key name");
|
||||
fireEvent.change(input, { target: { value: "123_token" } });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByRole("alert")).toBeTruthy();
|
||||
expect(screen.getByText(/upper_snake_case/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows error for key name starting with number", async () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("123_TOKEN");
|
||||
expect(screen.getByText(/upper_snake_case/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows duplicate error when key name already exists", async () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={["ANTHROPIC_API_KEY"]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("ANTHROPIC_API_KEY");
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByText(/already exists/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("no error for valid new key name", async () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("MY_SECRET_KEY");
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.queryByRole("alert")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Provider hint ──────────────────────────────────────────────────────────
|
||||
|
||||
describe("AddKeyForm — provider hint", () => {
|
||||
it("shows provider hint for ANTHROPIC_API_KEY (known provider)", async () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("ANTHROPIC_API_KEY");
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByTestId("provider-hint")).toBeTruthy();
|
||||
expect(screen.getByText("Anthropic")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows provider hint for GITHUB_TOKEN", async () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("GITHUB_TOKEN");
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByTestId("provider-hint")).toBeTruthy();
|
||||
expect(screen.getByText("GitHub")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows provider hint for OPENROUTER_API_KEY", async () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("OPENROUTER_API_KEY");
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByTestId("provider-hint")).toBeTruthy();
|
||||
expect(screen.getByText("OpenRouter")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("hides provider hint for unknown custom key name", async () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("MY_CUSTOM_TOKEN");
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.queryByTestId("provider-hint")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Value validation (debounced) ───────────────────────────────────────────
|
||||
|
||||
describe("AddKeyForm — value validation (debounced)", () => {
|
||||
it("ValidationHint shown after debounce for invalid value", async () => {
|
||||
vi.useFakeTimers();
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("ANTHROPIC_API_KEY");
|
||||
const textarea = screen.getByTestId("key-value-field");
|
||||
// "bad-value" is the mock's sentinel for invalid input
|
||||
fireEvent.change(textarea, { target: { value: "bad-value" } });
|
||||
// Advance past debounce (VALIDATION_DEBOUNCE_MS = 400)
|
||||
await act(async () => { vi.advanceTimersByTime(400); });
|
||||
expect(screen.getByRole("alert")).toBeTruthy();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Save ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("AddKeyForm — save", () => {
|
||||
it("Save button disabled when key name or value missing", () => {
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
const saveBtn = screen.getByRole("button", { name: /save key/i });
|
||||
expect((saveBtn as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("Save button enabled when valid key name + value", async () => {
|
||||
vi.useFakeTimers();
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("ANTHROPIC_API_KEY");
|
||||
await typeValue("GITHUB_FAKE_VALUE_FOR_TEST");
|
||||
await act(async () => { vi.advanceTimersByTime(400); });
|
||||
const saveBtn = screen.getByRole("button", { name: /save key/i });
|
||||
expect((saveBtn as HTMLButtonElement).disabled).toBe(false);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("calls createSecret(workspaceId, keyName, value) on save", async () => {
|
||||
vi.useFakeTimers();
|
||||
render(<AddKeyForm workspaceId="ws-test" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("ANTHROPIC_API_KEY");
|
||||
await typeValue("GITHUB_FAKE_VALUE_FOR_TEST");
|
||||
await act(async () => { vi.advanceTimersByTime(400); });
|
||||
fireEvent.click(screen.getByRole("button", { name: /save key/i }));
|
||||
await act(async () => { vi.advanceTimersByTime(0); });
|
||||
expect(mockCreateSecret).toHaveBeenCalledWith(
|
||||
"ws-test",
|
||||
"ANTHROPIC_API_KEY",
|
||||
"GITHUB_FAKE_VALUE_FOR_TEST",
|
||||
);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("Save button shows 'Saving…' during save", async () => {
|
||||
vi.useFakeTimers();
|
||||
mockCreateSecret.mockImplementation(() => new Promise(() => {}));
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("ANTHROPIC_API_KEY");
|
||||
await typeValue("GITHUB_FAKE_VALUE_FOR_TEST");
|
||||
await act(async () => { vi.advanceTimersByTime(400); });
|
||||
fireEvent.click(screen.getByRole("button", { name: /save key/i }));
|
||||
await act(async () => { vi.advanceTimersByTime(0); });
|
||||
expect(screen.getByRole("button", { name: /saving/i })).toBeTruthy();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("shows error on save failure", async () => {
|
||||
mockCreateSecret.mockRejectedValue(new Error("network error"));
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("ANTHROPIC_API_KEY");
|
||||
await typeValue("GITHUB_FAKE_VALUE_FOR_TEST");
|
||||
fireEvent.click(screen.getByRole("button", { name: /save key/i }));
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByText(/network error/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Cancel ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("AddKeyForm — cancel", () => {
|
||||
it("onCancel called when Cancel button clicked", () => {
|
||||
const onCancel = vi.fn();
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={onCancel} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /cancel/i }));
|
||||
expect(onCancel).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("Cancel button disabled during save", async () => {
|
||||
vi.useFakeTimers();
|
||||
mockCreateSecret.mockImplementation(() => new Promise(() => {}));
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("ANTHROPIC_API_KEY");
|
||||
await typeValue("GITHUB_FAKE_VALUE_FOR_TEST");
|
||||
await act(async () => { vi.advanceTimersByTime(400); });
|
||||
fireEvent.click(screen.getByRole("button", { name: /save key/i }));
|
||||
await act(async () => { vi.advanceTimersByTime(0); });
|
||||
expect((screen.getByRole("button", { name: /cancel/i }) as HTMLButtonElement).disabled).toBe(true);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── TestConnectionButton ────────────────────────────────────────────────────
|
||||
|
||||
describe("AddKeyForm — TestConnectionButton", () => {
|
||||
it("TestConnectionButton shown for known provider with valid-format value", async () => {
|
||||
vi.useFakeTimers();
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("ANTHROPIC_API_KEY");
|
||||
// Use a value that passes the regex (sk-ant- prefix + 90+ chars)
|
||||
const validValue = "GHP_FAKEPLACEHOLDER_NOTREAL_ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234567890";
|
||||
await typeValue(validValue);
|
||||
await act(async () => { vi.advanceTimersByTime(400); });
|
||||
expect(screen.getByTestId("test-connection-btn")).toBeTruthy();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("TestConnectionButton NOT shown when value is invalid format", async () => {
|
||||
vi.useFakeTimers();
|
||||
render(<AddKeyForm workspaceId="ws-1" existingNames={[]} onCancel={vi.fn()} />);
|
||||
await typeKeyName("ANTHROPIC_API_KEY");
|
||||
await typeValue("bad-value");
|
||||
await act(async () => { vi.advanceTimersByTime(400); });
|
||||
expect(screen.queryByTestId("test-connection-btn")).toBeNull();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
@@ -1,407 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for OrgTokensTab — org-scoped API key management.
|
||||
*
|
||||
* Covers:
|
||||
* - Loading state (spinner + aria-busy)
|
||||
* - Empty state when no tokens
|
||||
* - Token list rendering (single + multiple)
|
||||
* - Token age display (just now, minutes, hours, days)
|
||||
* - New key form: label input + Create button
|
||||
* - Create: POST with optional name payload
|
||||
* - Create: loading spinner during creation
|
||||
* - New-token success box with copy button
|
||||
* - Copy button writes to clipboard + shows "Copied"
|
||||
* - Copy auto-resets to "Copy" after 2s
|
||||
* - Dismiss button hides new-token box
|
||||
* - Revoke button opens ConfirmDialog
|
||||
* - ConfirmDialog cancel closes without calling API
|
||||
* - ConfirmDialog confirm calls DELETE and re-fetches
|
||||
* - Error banner on fetch failure
|
||||
* - Error banner on create failure
|
||||
* - Error banner on revoke failure
|
||||
*/
|
||||
import React from "react";
|
||||
import { render, screen, fireEvent, cleanup, act, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { OrgTokensTab } from "../OrgTokensTab";
|
||||
|
||||
vi.mock("@/components/ConfirmDialog", () => ({
|
||||
ConfirmDialog: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
const mockGet = vi.fn();
|
||||
const mockPost = vi.fn();
|
||||
const mockDel = vi.fn();
|
||||
|
||||
vi.mock("@/lib/api", () => ({
|
||||
api: { get: (...args: unknown[]) => mockGet(...args), post: (...args: unknown[]) => mockPost(...args), del: (...args: unknown[]) => mockDel(...args) },
|
||||
}));
|
||||
|
||||
// Stub clipboard
|
||||
vi.stubGlobal("navigator", { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useRealTimers();
|
||||
mockGet.mockReset();
|
||||
mockPost.mockReset();
|
||||
mockDel.mockReset();
|
||||
vi.mocked(navigator.clipboard.writeText).mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
async function flush() {
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
}
|
||||
|
||||
function token(overrides: Partial<{
|
||||
id: string; prefix: string; name?: string; created_by?: string; created_at: string; last_used_at?: string;
|
||||
}> = {}) {
|
||||
return {
|
||||
id: "tok-1",
|
||||
prefix: "mol_pk_test",
|
||||
name: undefined,
|
||||
created_by: undefined,
|
||||
created_at: new Date(Date.now() - 120_000).toISOString(),
|
||||
last_used_at: undefined,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Loading ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("OrgTokensTab — loading", () => {
|
||||
it("shows spinner while fetching", () => {
|
||||
mockGet.mockImplementation(() => new Promise(() => {}));
|
||||
render(<OrgTokensTab />);
|
||||
expect(screen.getByRole("status")).toBeTruthy();
|
||||
expect(screen.getByText("Loading keys...")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("loading indicator has role=status and aria-live=polite", () => {
|
||||
mockGet.mockImplementation(() => new Promise(() => {}));
|
||||
render(<OrgTokensTab />);
|
||||
const status = screen.getByRole("status");
|
||||
expect(status.getAttribute("aria-live")).toBe("polite");
|
||||
expect(status.textContent).toContain("Loading keys");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Empty state ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("OrgTokensTab — empty", () => {
|
||||
it("shows empty state when no tokens", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.getByText("No active keys")).toBeTruthy();
|
||||
expect(screen.getByText(/Create a key above to authenticate/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Token list ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("OrgTokensTab — token list", () => {
|
||||
it("renders token rows", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [token({ id: "tok-1", prefix: "mol_pk_abc" })], count: 1 });
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.getByText(/mol_pk_abc/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders multiple token rows", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
tokens: [
|
||||
token({ id: "tok-1", prefix: "mol_pk_a" }),
|
||||
token({ id: "tok-2", prefix: "mol_pk_b" }),
|
||||
],
|
||||
count: 2,
|
||||
});
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.getByText(/mol_pk_a/)).toBeTruthy();
|
||||
expect(screen.getByText(/mol_pk_b/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows token name when present", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
tokens: [token({ id: "tok-1", prefix: "mol_pk_abc", name: "zapier-integration" })],
|
||||
count: 1,
|
||||
});
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.getByText("zapier-integration")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("age shows 'just now' for very recent tokens", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
tokens: [token({ id: "tok-1", created_at: new Date().toISOString() })],
|
||||
count: 1,
|
||||
});
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.getByText(/just now/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("age shows minutes ago", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
tokens: [token({ id: "tok-1", created_at: new Date(Date.now() - 5 * 60_000).toISOString() })],
|
||||
count: 1,
|
||||
});
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.getByText(/5m ago/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("age shows hours ago", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
tokens: [token({ id: "tok-1", created_at: new Date(Date.now() - 3 * 3600_000).toISOString() })],
|
||||
count: 1,
|
||||
});
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.getByText(/3h ago/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("age shows days ago", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
tokens: [token({ id: "tok-1", created_at: new Date(Date.now() - 2 * 86400_000).toISOString() })],
|
||||
count: 1,
|
||||
});
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.getByText(/2d ago/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("each token has a Revoke button", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
tokens: [token({ id: "tok-1" }), token({ id: "tok-2" })],
|
||||
count: 2,
|
||||
});
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
const revokeBtns = Array.from(document.querySelectorAll("button")).filter(b => b.textContent === "Revoke");
|
||||
expect(revokeBtns.length).toBe(2);
|
||||
});
|
||||
|
||||
it("last_used_at is shown when present", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
tokens: [token({
|
||||
id: "tok-1",
|
||||
created_at: new Date(Date.now() - 86400_000).toISOString(),
|
||||
last_used_at: new Date(Date.now() - 3600_000).toISOString(),
|
||||
})],
|
||||
count: 1,
|
||||
});
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.getByText(/Last used/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Create token ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("OrgTokensTab — create", () => {
|
||||
it("Create button calls POST with empty body when no label", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
mockPost.mockResolvedValue({ auth_token: "tok_new_secret", prefix: "tok_new" });
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
const createBtn = screen.getByRole("button", { name: "+ New Key" });
|
||||
await act(async () => { createBtn.click(); });
|
||||
await flush();
|
||||
expect(mockPost).toHaveBeenCalledWith("/org/tokens", {});
|
||||
});
|
||||
|
||||
it("Create button calls POST with name when label is filled", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
mockPost.mockResolvedValue({ auth_token: "tok_new_secret", prefix: "tok_new" });
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
const input = screen.getByRole("textbox");
|
||||
fireEvent.change(input, { target: { value: "zapier-prod" } });
|
||||
await act(async () => { screen.getByRole("button", { name: "+ New Key" }).click(); });
|
||||
await flush();
|
||||
expect(mockPost).toHaveBeenCalledWith("/org/tokens", { name: "zapier-prod" });
|
||||
});
|
||||
|
||||
it("shows spinner while creating", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
mockPost.mockImplementation(() => new Promise(() => {}));
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
await act(async () => { screen.getByRole("button", { name: "+ New Key" }).click(); });
|
||||
await flush();
|
||||
expect(screen.getByText(/Creating/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows new token box after creation", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
mockPost.mockResolvedValue({ auth_token: "tok_new_secret_xyz", prefix: "tok_new" });
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
await act(async () => { screen.getByRole("button", { name: "+ New Key" }).click(); });
|
||||
await flush();
|
||||
expect(screen.getByText(/tok_new_secret_xyz/)).toBeTruthy();
|
||||
expect(screen.getByText(/Copy now/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("new token shows label when provided", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
mockPost.mockResolvedValue({ auth_token: "tok_abc123", prefix: "tok_abc" });
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
const input = screen.getByRole("textbox");
|
||||
fireEvent.change(input, { target: { value: "my-label" } });
|
||||
await act(async () => { screen.getByRole("button", { name: "+ New Key" }).click(); });
|
||||
await flush();
|
||||
expect(screen.getByText(/New Key: my-label/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("dismiss hides the new-token box", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
mockPost.mockResolvedValue({ auth_token: "tok_dismiss", prefix: "tok_d" });
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
await act(async () => { screen.getByRole("button", { name: "+ New Key" }).click(); });
|
||||
await flush();
|
||||
expect(screen.getByText(/tok_dismiss/)).toBeTruthy();
|
||||
await act(async () => { screen.getByText("Dismiss").closest("button")!.click(); });
|
||||
await flush();
|
||||
expect(screen.queryByText(/tok_dismiss/)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Copy button ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("OrgTokensTab — copy", () => {
|
||||
it("Copy button writes token to clipboard", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
mockPost.mockResolvedValue({ auth_token: "tok_copy_test", prefix: "tok_c" });
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
await act(async () => { screen.getByRole("button", { name: "+ New Key" }).click(); });
|
||||
await flush();
|
||||
const copyBtn = screen.getByRole("button", { name: "Copy" });
|
||||
await act(async () => { copyBtn.click(); });
|
||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith("tok_copy_test");
|
||||
});
|
||||
|
||||
it("Copy button shows 'Copied' after click", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
mockPost.mockResolvedValue({ auth_token: "tok_copy_2", prefix: "tok_c" });
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
await act(async () => { screen.getByRole("button", { name: "+ New Key" }).click(); });
|
||||
await flush();
|
||||
await act(async () => { screen.getByRole("button", { name: "Copy" }).click(); });
|
||||
await flush();
|
||||
expect(screen.getByRole("button", { name: "Copied" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Copy resets to 'Copy' after 2s", async () => {
|
||||
vi.useFakeTimers();
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
mockPost.mockResolvedValue({ auth_token: "tok_timer", prefix: "tok_t" });
|
||||
render(<OrgTokensTab />);
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
await act(async () => { screen.getByRole("button", { name: "+ New Key" }).click(); });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
await act(async () => { screen.getByRole("button", { name: "Copy" }).click(); });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByRole("button", { name: "Copied" })).toBeTruthy();
|
||||
act(() => { vi.advanceTimersByTime(2000); });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByRole("button", { name: "Copy" })).toBeTruthy();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Revoke ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("OrgTokensTab — revoke", () => {
|
||||
it("Revoke button opens ConfirmDialog", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [token({ id: "tok-revoke", prefix: "mol_pk_rev" })], count: 1 });
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
await act(async () => {
|
||||
Array.from(document.querySelectorAll("button")).find(b => b.textContent === "Revoke")!.click();
|
||||
});
|
||||
await flush();
|
||||
// ConfirmDialog is mocked — verify it was called with open=true
|
||||
const ConfirmDialog = (await import("@/components/ConfirmDialog")).ConfirmDialog as ReturnType<typeof vi.fn>;
|
||||
const lastCall = ConfirmDialog.mock.calls[ConfirmDialog.mock.calls.length - 1];
|
||||
expect(lastCall[0]).toMatchObject({ open: true, title: "Revoke API Key" });
|
||||
});
|
||||
|
||||
it("DELETE is called with correct URL on confirm", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [token({ id: "tok-del", prefix: "mol_pk_del" })], count: 1 });
|
||||
mockDel.mockResolvedValue(undefined);
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
|
||||
// Open confirm
|
||||
await act(async () => {
|
||||
Array.from(document.querySelectorAll("button")).find(b => b.textContent === "Revoke")!.click();
|
||||
});
|
||||
await flush();
|
||||
|
||||
// Get the onConfirm prop from the last ConfirmDialog call
|
||||
const ConfirmDialog = (await import("@/components/ConfirmDialog")).ConfirmDialog as ReturnType<typeof vi.fn>;
|
||||
const lastCall = ConfirmDialog.mock.calls[ConfirmDialog.mock.calls.length - 1];
|
||||
const onConfirm = lastCall[0]?.onConfirm;
|
||||
|
||||
// Call onConfirm
|
||||
await act(async () => { onConfirm?.(); });
|
||||
await flush();
|
||||
|
||||
expect(mockDel).toHaveBeenCalledWith("/org/tokens/tok-del");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Error states ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("OrgTokensTab — errors", () => {
|
||||
it("shows error when fetch fails", async () => {
|
||||
mockGet.mockRejectedValue(new Error("network failure"));
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
expect(screen.getByText(/network failure/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows error when create fails", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [], count: 0 });
|
||||
mockPost.mockRejectedValue(new Error("server error"));
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
await act(async () => { screen.getByRole("button", { name: "+ New Key" }).click(); });
|
||||
await flush();
|
||||
expect(screen.getByText(/server error/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows error when revoke fails", async () => {
|
||||
mockGet.mockResolvedValue({ tokens: [token({ id: "tok-err" })], count: 1 });
|
||||
mockDel.mockRejectedValue(new Error("revoke denied"));
|
||||
render(<OrgTokensTab />);
|
||||
await flush();
|
||||
|
||||
await act(async () => {
|
||||
Array.from(document.querySelectorAll("button")).find(b => b.textContent === "Revoke")!.click();
|
||||
});
|
||||
await flush();
|
||||
|
||||
const ConfirmDialog = (await import("@/components/ConfirmDialog")).ConfirmDialog as ReturnType<typeof vi.fn>;
|
||||
const onConfirm = ConfirmDialog.mock.calls[ConfirmDialog.mock.calls.length - 1][0]?.onConfirm;
|
||||
await act(async () => { onConfirm?.(); });
|
||||
await flush();
|
||||
|
||||
expect(screen.getByText(/revoke denied/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,291 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for SecretRow — single secret display/edit row.
|
||||
*
|
||||
* Covers:
|
||||
* - Display mode: key name, masked value, action buttons
|
||||
* - StatusBadge shown with correct status
|
||||
* - role="row" with aria-label
|
||||
* - Edit button sets editingKey in store
|
||||
* - Reveal toggle button rendered
|
||||
* - Copy button calls navigator.clipboard.writeText
|
||||
* - Delete button dispatches secret:delete-request event
|
||||
* - Edit mode: KeyValueField + save/cancel rendered
|
||||
* - Cancel calls setEditingKey(null)
|
||||
* - Save calls updateSecret + setSecretStatus
|
||||
* - Save error shown on failure
|
||||
* - TestConnectionButton shown when testSupported + value entered
|
||||
*/
|
||||
import React from "react";
|
||||
import { render, screen, fireEvent, cleanup, act } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SecretRow } from "../SecretRow";
|
||||
|
||||
// ── Hoisted mocks — vi.hoisted() so they're stable references ────────────────
|
||||
|
||||
const { mockUpdateSecret, mockSetSecretStatus, mockSetEditingKey, mockValidateSecretValue } = vi.hoisted(() => ({
|
||||
mockUpdateSecret: vi.fn(),
|
||||
mockSetSecretStatus: vi.fn(),
|
||||
mockSetEditingKey: vi.fn(),
|
||||
mockValidateSecretValue: vi.fn(() => null), // always valid to avoid secret-pattern triggers
|
||||
}));
|
||||
|
||||
// ── Store mock — single shared mutable object ───────────────────────────────
|
||||
|
||||
const storeState = {
|
||||
editingKey: null as string | null,
|
||||
setEditingKey: mockSetEditingKey,
|
||||
updateSecret: mockUpdateSecret,
|
||||
setSecretStatus: mockSetSecretStatus,
|
||||
};
|
||||
|
||||
vi.mock("@/stores/secrets-store", () => ({
|
||||
useSecretsStore: Object.assign(
|
||||
vi.fn((selector?: (s: typeof storeState) => unknown) =>
|
||||
selector ? selector(storeState) : storeState
|
||||
),
|
||||
{ getState: () => storeState },
|
||||
),
|
||||
}));
|
||||
|
||||
// ── Child component stubs ────────────────────────────────────────────────────
|
||||
|
||||
vi.mock("@/lib/validation/secret-formats", () => ({
|
||||
validateSecretValue: mockValidateSecretValue,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/StatusBadge", () => ({
|
||||
StatusBadge: ({ status }: { status: string }) => (
|
||||
<span data-testid="status-badge" data-status={status}>{status}</span>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/RevealToggle", () => ({
|
||||
RevealToggle: ({ revealed, onToggle, label }: { revealed: boolean; onToggle: () => void; label: string }) => (
|
||||
<button type="button" data-testid="reveal-toggle" aria-label={label} onClick={onToggle}>
|
||||
{revealed ? "HIDE" : "REVEAL"}
|
||||
</button>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/KeyValueField", () => ({
|
||||
KeyValueField: ({ value, onChange, disabled }: { value: string; onChange: (v: string) => void; disabled?: boolean }) => (
|
||||
<textarea
|
||||
data-testid="edit-value-field"
|
||||
value={value}
|
||||
onChange={(e) => { onChange(e.target.value); }}
|
||||
disabled={disabled}
|
||||
/>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/ValidationHint", () => ({
|
||||
ValidationHint: ({ error }: { error: string | null }) =>
|
||||
error ? <span role="alert">{error}</span> : null,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/TestConnectionButton", () => ({
|
||||
TestConnectionButton: () => <button data-testid="test-connection-btn" type="button">Test connection</button>,
|
||||
}));
|
||||
|
||||
// ── Test data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const GITHUB_SECRET = { name: "GITHUB_TOKEN", masked_value: "ghp_••••••••••••xK9f", group: "github" as const, status: "verified" as const, updated_at: "2024-01-01" };
|
||||
const ANTHROPIC_SECRET = { name: "ANTHROPIC_API_KEY", masked_value: "sk-ant-•••••••••••••••••a3Zq", group: "anthropic" as const, status: "unverified" as const, updated_at: "2024-01-02" };
|
||||
const CUSTOM_SECRET = { name: "MY_CUSTOM_KEY", masked_value: "••••••••••••••••9d2a", group: "custom" as const, status: "invalid" as const, updated_at: "2024-01-03" };
|
||||
|
||||
// Use a value that definitely does NOT match any secret format regex
|
||||
const EDIT_VALUE = "TEST_VALID_TOKEN_VALUE_PLACEHOLDER_FOR_EDIT_MODE";
|
||||
|
||||
beforeEach(() => {
|
||||
// Mutate the shared object so all closures see the update
|
||||
storeState.editingKey = null;
|
||||
storeState.setEditingKey = vi.fn();
|
||||
storeState.updateSecret = vi.fn().mockResolvedValue(undefined);
|
||||
storeState.setSecretStatus = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
// ─── Display mode ───────────────────────────────────────────────────────────
|
||||
|
||||
describe("SecretRow — display mode", () => {
|
||||
it("shows secret name", () => {
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
expect(screen.getByText("GITHUB_TOKEN")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows masked value", () => {
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
expect(screen.getByText("ghp_••••••••••••xK9f")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows StatusBadge", () => {
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
expect(screen.getByTestId("status-badge")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("StatusBadge has correct data-status attribute", () => {
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
expect(screen.getByTestId("status-badge").getAttribute("data-status")).toBe("verified");
|
||||
});
|
||||
|
||||
it("role=row", () => {
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
expect(document.querySelector('[role="row"]')).toBeTruthy();
|
||||
});
|
||||
|
||||
it("has Reveal, Copy, Edit, Delete buttons", () => {
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
expect(screen.getByTestId("reveal-toggle")).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /copy/i })).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /edit/i })).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /delete/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows invalid status correctly", () => {
|
||||
render(<SecretRow secret={CUSTOM_SECRET} workspaceId="ws-1" />);
|
||||
expect(screen.getByTestId("status-badge").getAttribute("data-status")).toBe("invalid");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Edit ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SecretRow — edit", () => {
|
||||
it("Edit button calls setEditingKey(secret.name)", () => {
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
expect(storeState.setEditingKey).toHaveBeenCalledWith("GITHUB_TOKEN");
|
||||
});
|
||||
|
||||
it("shows edit form (KeyValueField + save/cancel) when editingKey set", () => {
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
expect(screen.getByTestId("edit-value-field")).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /cancel/i })).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /save/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Cancel calls setEditingKey(null)", () => {
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /cancel/i }));
|
||||
expect(storeState.setEditingKey).toHaveBeenCalledWith(null);
|
||||
});
|
||||
|
||||
it("Save button disabled when editValue is empty", () => {
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
expect((screen.getByRole("button", { name: /save/i }) as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("Save enabled when editValue is non-empty", async () => {
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-abc" />);
|
||||
const textarea = screen.getByTestId("edit-value-field");
|
||||
fireEvent.change(textarea, { target: { value: EDIT_VALUE } });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect((screen.getByRole("button", { name: /save/i }) as HTMLButtonElement).disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("Save calls updateSecret(workspaceId, name, editValue)", async () => {
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-test" />);
|
||||
fireEvent.change(screen.getByTestId("edit-value-field"), { target: { value: EDIT_VALUE } });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
fireEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(storeState.updateSecret).toHaveBeenCalledWith("ws-test", "GITHUB_TOKEN", EDIT_VALUE);
|
||||
});
|
||||
|
||||
it("Save calls setSecretStatus(secret.name, 'unverified')", async () => {
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
fireEvent.change(screen.getByTestId("edit-value-field"), { target: { value: EDIT_VALUE } });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
fireEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(storeState.setSecretStatus).toHaveBeenCalledWith("GITHUB_TOKEN", "unverified");
|
||||
});
|
||||
|
||||
it("Save button shows 'Saving…' during pending save", async () => {
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
storeState.updateSecret = vi.fn(() => new Promise(() => {}));
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
fireEvent.change(screen.getByTestId("edit-value-field"), { target: { value: EDIT_VALUE } });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
fireEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByText("Saving…")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows error on save failure", async () => {
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
storeState.updateSecret = vi.fn().mockRejectedValue(new Error("network error"));
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
fireEvent.change(screen.getByTestId("edit-value-field"), { target: { value: EDIT_VALUE } });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
fireEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByText(/network error/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Copy ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SecretRow — copy", () => {
|
||||
it("Copy calls navigator.clipboard.writeText with masked value", async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
value: { writeText },
|
||||
configurable: true,
|
||||
});
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /copy/i }));
|
||||
expect(writeText).toHaveBeenCalledWith("ghp_••••••••••••xK9f");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Delete ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SecretRow — delete", () => {
|
||||
it("Delete dispatches secret:delete-request with secret name", () => {
|
||||
const listener = vi.fn();
|
||||
window.addEventListener("secret:delete-request", listener);
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /delete/i }));
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ detail: "GITHUB_TOKEN" })
|
||||
);
|
||||
window.removeEventListener("secret:delete-request", listener);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── TestConnectionButton ────────────────────────────────────────────────────
|
||||
|
||||
describe("SecretRow — TestConnectionButton", () => {
|
||||
it("shown for github secret when editValue is entered", async () => {
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
fireEvent.change(screen.getByTestId("edit-value-field"), { target: { value: EDIT_VALUE } });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByTestId("test-connection-btn")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("NOT shown for custom secret (testSupported=false)", async () => {
|
||||
storeState.editingKey = "MY_CUSTOM_KEY";
|
||||
render(<SecretRow secret={CUSTOM_SECRET} workspaceId="ws-1" />);
|
||||
fireEvent.change(screen.getByTestId("edit-value-field"), { target: { value: EDIT_VALUE } });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.queryByTestId("test-connection-btn")).toBeNull();
|
||||
});
|
||||
|
||||
it("NOT shown when editValue is empty", () => {
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
render(<SecretRow secret={GITHUB_SECRET} workspaceId="ws-1" />);
|
||||
expect(screen.queryByTestId("test-connection-btn")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,308 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for SecretsTab — API keys tab inside SettingsPanel.
|
||||
*
|
||||
* Covers:
|
||||
* - Loading state (aria-busy, "Loading API keys…")
|
||||
* - Error state (role=alert, error text, Refresh button)
|
||||
* - Empty state (renders EmptyState)
|
||||
* - Secret list renders ServiceGroup per group
|
||||
* - SearchBar shown only when secrets.length >= 4
|
||||
* - Search filters results — no-results state + Clear search
|
||||
* - "+ Add API Key" button toggles AddKeyForm
|
||||
* - AddKeyForm visible when isAddFormOpen=true
|
||||
* - ServiceGroup with multiple groups rendered
|
||||
* - Single-key group count label ("1 key")
|
||||
* - Multi-key group count label ("N keys")
|
||||
*/
|
||||
import React from "react";
|
||||
import { render, screen, fireEvent, cleanup, act, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SecretsTab } from "../SecretsTab";
|
||||
|
||||
// ── Secrets store mock ───────────────────────────────────────────────────────
|
||||
|
||||
type SecretsStoreState = {
|
||||
secrets: Array<{ name: string; masked_value: string; group: string; status: string; updated_at: string }>;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
isAddFormOpen: boolean;
|
||||
searchQuery: string;
|
||||
fetchSecrets: ReturnType<typeof vi.fn>;
|
||||
setAddFormOpen: ReturnType<typeof vi.fn>;
|
||||
setSearchQuery: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
// Mutable store state — tests reassign fields to test different states
|
||||
let storeState: SecretsStoreState;
|
||||
|
||||
const mockFetchSecrets = vi.fn().mockResolvedValue(undefined);
|
||||
const mockSetAddFormOpen = vi.fn();
|
||||
const mockSetSearchQuery = vi.fn();
|
||||
|
||||
storeState = {
|
||||
secrets: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
isAddFormOpen: false,
|
||||
searchQuery: "",
|
||||
fetchSecrets: mockFetchSecrets,
|
||||
setAddFormOpen: mockSetAddFormOpen,
|
||||
setSearchQuery: mockSetSearchQuery,
|
||||
};
|
||||
|
||||
vi.mock("@/stores/secrets-store", () => ({
|
||||
useSecretsStore: Object.assign(
|
||||
vi.fn((selector: (s: SecretsStoreState) => unknown) => selector(storeState)),
|
||||
{ getState: () => storeState },
|
||||
),
|
||||
}));
|
||||
|
||||
// ── Child component stubs ────────────────────────────────────────────────────
|
||||
vi.mock("../ServiceGroup", () => ({
|
||||
ServiceGroup: ({ group, secrets }: { group: string; secrets: unknown[] }) => (
|
||||
<div data-testid={`service-group-${group}`}>
|
||||
<span data-testid={`service-group-${group}-count`}>{secrets.length}</span>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("../EmptyState", () => ({
|
||||
EmptyState: ({ onAddFirst }: { onAddFirst: () => void }) => (
|
||||
<div data-testid="secrets-empty-state">
|
||||
<button onClick={onAddFirst}>Add first key</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("../AddKeyForm", () => ({
|
||||
AddKeyForm: ({ workspaceId, onCancel }: { workspaceId: string; onCancel: () => void }) => (
|
||||
<div data-testid="add-key-form">AddKeyForm workspaceId={workspaceId} <button onClick={onCancel}>Cancel</button></div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("../SearchBar", () => ({
|
||||
SearchBar: () => <div data-testid="search-bar" />,
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
storeState = {
|
||||
secrets: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
isAddFormOpen: false,
|
||||
searchQuery: "",
|
||||
fetchSecrets: mockFetchSecrets,
|
||||
setAddFormOpen: mockSetAddFormOpen,
|
||||
setSearchQuery: mockSetSearchQuery,
|
||||
};
|
||||
mockFetchSecrets.mockReset().mockResolvedValue(undefined);
|
||||
mockSetAddFormOpen.mockReset();
|
||||
mockSetSearchQuery.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
async function flush() {
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
}
|
||||
|
||||
// ─── Loading ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SecretsTab — loading", () => {
|
||||
it("shows loading state", () => {
|
||||
storeState.isLoading = true;
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByText("Loading API keys…")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Error ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SecretsTab — error", () => {
|
||||
it("shows error with role=alert", () => {
|
||||
storeState.error = "network failure";
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByRole("alert")).toBeTruthy();
|
||||
expect(screen.getByText("network failure")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows Refresh button in error state", () => {
|
||||
storeState.error = "server error";
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByRole("button", { name: "Refresh" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Refresh button calls fetchSecrets with workspaceId", () => {
|
||||
storeState.error = "server error";
|
||||
render(<SecretsTab workspaceId="ws-123" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refresh" }));
|
||||
expect(mockFetchSecrets).toHaveBeenCalledWith("ws-123");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Empty state ────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SecretsTab — empty", () => {
|
||||
it("shows EmptyState when secrets is empty and not loading", () => {
|
||||
storeState.secrets = [];
|
||||
storeState.isLoading = false;
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByTestId("secrets-empty-state")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("EmptyState Add first button opens add form", () => {
|
||||
storeState.secrets = [];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
fireEvent.click(screen.getByText("Add first key"));
|
||||
expect(mockSetAddFormOpen).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Secret list ────────────────────────────────────────────────────────────
|
||||
|
||||
describe("SecretsTab — secret list", () => {
|
||||
const ANTHROPIC_SECRET = { name: "ANTHROPIC_API_KEY", masked_value: "sk-ant-••••", group: "anthropic", status: "active", updated_at: "2024-01-01" };
|
||||
const GITHUB_SECRET = { name: "GITHUB_TOKEN", masked_value: "ghp_••••", group: "github", status: "active", updated_at: "2024-01-02" };
|
||||
const OPENROUTER_SECRET = { name: "OPENROUTER_API_KEY", masked_value: "sk-or-••••", group: "openrouter", status: "active", updated_at: "2024-01-03" };
|
||||
const CUSTOM_SECRET = { name: "MY_CUSTOM_KEY", masked_value: "••••", group: "custom", status: "active", updated_at: "2024-01-04" };
|
||||
|
||||
it("renders one ServiceGroup per non-empty group", () => {
|
||||
storeState.secrets = [ANTHROPIC_SECRET, GITHUB_SECRET];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByTestId("service-group-anthropic")).toBeTruthy();
|
||||
expect(screen.getByTestId("service-group-github")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does NOT render empty groups", () => {
|
||||
storeState.secrets = [ANTHROPIC_SECRET]; // only anthropic has secrets
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.queryByTestId("service-group-github")).toBeNull();
|
||||
expect(screen.queryByTestId("service-group-openrouter")).toBeNull();
|
||||
});
|
||||
|
||||
it("renders all 4 groups when all are populated", () => {
|
||||
storeState.secrets = [ANTHROPIC_SECRET, GITHUB_SECRET, OPENROUTER_SECRET, CUSTOM_SECRET];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByTestId("service-group-anthropic")).toBeTruthy();
|
||||
expect(screen.getByTestId("service-group-github")).toBeTruthy();
|
||||
expect(screen.getByTestId("service-group-openrouter")).toBeTruthy();
|
||||
expect(screen.getByTestId("service-group-custom")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows '+ Add API Key' button", () => {
|
||||
storeState.secrets = [ANTHROPIC_SECRET];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByRole("button", { name: /add api key/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("'+ Add API Key' opens AddKeyForm", () => {
|
||||
storeState.secrets = [ANTHROPIC_SECRET];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /add api key/i }));
|
||||
expect(mockSetAddFormOpen).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it("shows AddKeyForm when isAddFormOpen=true", () => {
|
||||
storeState.secrets = [ANTHROPIC_SECRET];
|
||||
storeState.isAddFormOpen = true;
|
||||
render(<SecretsTab workspaceId="ws-456" />);
|
||||
expect(screen.getByTestId("add-key-form")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("AddKeyForm Cancel closes the form", () => {
|
||||
storeState.secrets = [ANTHROPIC_SECRET];
|
||||
storeState.isAddFormOpen = true;
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
fireEvent.click(screen.getByText("Cancel"));
|
||||
expect(mockSetAddFormOpen).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("shows SearchBar when secrets.length >= 4", () => {
|
||||
storeState.secrets = [
|
||||
ANTHROPIC_SECRET, GITHUB_SECRET, OPENROUTER_SECRET,
|
||||
{ ...CUSTOM_SECRET, name: "EXTRA_KEY_1" },
|
||||
];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByTestId("search-bar")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("hides SearchBar when secrets.length < 4", () => {
|
||||
storeState.secrets = [ANTHROPIC_SECRET, GITHUB_SECRET];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.queryByTestId("search-bar")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Search / filtering ──────────────────────────────────────────────────────
|
||||
|
||||
describe("SecretsTab — search", () => {
|
||||
const S1 = { name: "ANTHROPIC_API_KEY", masked_value: "sk-ant-••••", group: "anthropic", status: "active", updated_at: "2024-01-01" };
|
||||
const S2 = { name: "GITHUB_TOKEN", masked_value: "ghp_••••", group: "github", status: "active", updated_at: "2024-01-02" };
|
||||
const S3 = { name: "OPENROUTER_API_KEY", masked_value: "sk-or-••••", group: "openrouter", status: "active", updated_at: "2024-01-03" };
|
||||
const S4 = { name: "MY_CUSTOM_KEY", masked_value: "••••", group: "custom", status: "active", updated_at: "2024-01-04" };
|
||||
|
||||
beforeEach(() => {
|
||||
// Need 4+ secrets for SearchBar to appear
|
||||
storeState.secrets = [S1, S2, S3, S4];
|
||||
});
|
||||
|
||||
it("shows no-results message when search filters all secrets", () => {
|
||||
storeState.searchQuery = "nonexistent-key";
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByText(/no keys match/i)).toBeTruthy();
|
||||
expect(screen.getByText(/nonexistent-key/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows 'Clear search' button in no-results state", () => {
|
||||
storeState.searchQuery = "nonexistent";
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByRole("button", { name: /clear search/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("'Clear search' clears searchQuery via store.getState()", () => {
|
||||
storeState.searchQuery = "nonexistent";
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /clear search/i }));
|
||||
expect(mockSetSearchQuery).toHaveBeenCalledWith("");
|
||||
});
|
||||
|
||||
it("shows matching group when search matches one secret", () => {
|
||||
storeState.searchQuery = "anthropic";
|
||||
storeState.secrets = [S1, S2, S3, S4];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByTestId("service-group-anthropic")).toBeTruthy();
|
||||
// Other groups should be filtered out
|
||||
expect(screen.queryByTestId("service-group-github")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── SearchBar visibility threshold ─────────────────────────────────────────
|
||||
|
||||
describe("SecretsTab — search bar threshold", () => {
|
||||
const makeSecret = (n: number) => ({
|
||||
name: `KEY_${n}`, masked_value: "••••", group: "custom" as const, status: "active" as const, updated_at: "2024-01-01",
|
||||
});
|
||||
|
||||
it("SearchBar hidden at 3 secrets", () => {
|
||||
storeState.secrets = [makeSecret(1), makeSecret(2), makeSecret(3)];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.queryByTestId("search-bar")).toBeNull();
|
||||
});
|
||||
|
||||
it("SearchBar shown at 4 secrets (threshold)", () => {
|
||||
storeState.secrets = [makeSecret(1), makeSecret(2), makeSecret(3), makeSecret(4)];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.getByTestId("search-bar")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("SearchBar hidden when secrets drop to 3 below threshold", () => {
|
||||
// Separate render with 3 secrets — plain object state won't
|
||||
// re-render React on mutation, so test the logic directly.
|
||||
storeState.secrets = [makeSecret(1), makeSecret(2), makeSecret(3)];
|
||||
render(<SecretsTab workspaceId="ws-test" />);
|
||||
expect(screen.queryByTestId("search-bar")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,233 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for SettingsPanel — right-anchored slide-over drawer for workspace settings.
|
||||
*
|
||||
* Covers:
|
||||
* - Closed by default (Dialog closed when isPanelOpen=false)
|
||||
* - Opens when isPanelOpen=true
|
||||
* - Three tabs: Secrets, Workspace Tokens, Org API Keys
|
||||
* - Cmd+, keyboard shortcut toggles panel
|
||||
* - Clicking backdrop/close with dirty form (editingKey set) shows UnsavedChangesGuard
|
||||
* - Guard "Keep editing" closes guard (does NOT close panel)
|
||||
* - Guard "Discard" closes guard AND closes panel
|
||||
* - fetchSecrets called when panel opens
|
||||
* - Close button closes panel
|
||||
* - aria-modal="false" — canvas stays interactive
|
||||
*/
|
||||
import React from "react";
|
||||
import { render, screen, fireEvent, cleanup, act, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SettingsPanel } from "../SettingsPanel";
|
||||
|
||||
// ── Store mock ──────────────────────────────────────────────────────────────
|
||||
|
||||
type PanelStoreState = {
|
||||
isPanelOpen: boolean;
|
||||
isAddFormOpen: boolean;
|
||||
editingKey: string | null;
|
||||
closePanel: () => void;
|
||||
openPanel: () => void;
|
||||
fetchSecrets: (workspaceId: string) => Promise<void>;
|
||||
};
|
||||
|
||||
let storeState: PanelStoreState;
|
||||
const mockClosePanel = vi.fn();
|
||||
const mockOpenPanel = vi.fn();
|
||||
const mockFetchSecrets = vi.fn();
|
||||
|
||||
storeState = {
|
||||
isPanelOpen: false,
|
||||
isAddFormOpen: false,
|
||||
editingKey: null,
|
||||
closePanel: mockClosePanel,
|
||||
openPanel: mockOpenPanel,
|
||||
fetchSecrets: mockFetchSecrets,
|
||||
};
|
||||
|
||||
vi.mock("@/stores/secrets-store", () => ({
|
||||
useSecretsStore: Object.assign(
|
||||
vi.fn((selector?: (s: PanelStoreState) => unknown) =>
|
||||
selector ? selector(storeState) : storeState
|
||||
),
|
||||
{ getState: () => storeState },
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/use-keyboard-shortcut", () => ({
|
||||
useKeyboardShortcut: vi.fn(),
|
||||
}));
|
||||
|
||||
// ── Child component stubs ────────────────────────────────────────────────────
|
||||
|
||||
vi.mock("../SecretsTab", () => ({
|
||||
SecretsTab: ({ workspaceId }: { workspaceId: string }) => (
|
||||
<div data-testid="secrets-tab">SecretsTab workspaceId={workspaceId}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("../TokensTab", () => ({
|
||||
TokensTab: ({ workspaceId }: { workspaceId: string }) => (
|
||||
<div data-testid="tokens-tab">TokensTab workspaceId={workspaceId}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("../OrgTokensTab", () => ({
|
||||
OrgTokensTab: () => <div data-testid="org-tokens-tab">OrgTokensTab</div>,
|
||||
}));
|
||||
|
||||
vi.mock("../UnsavedChangesGuard", () => ({
|
||||
UnsavedChangesGuard: ({ open, onKeepEditing, onDiscard }: {
|
||||
open: boolean;
|
||||
onKeepEditing: () => void;
|
||||
onDiscard: () => void;
|
||||
}) =>
|
||||
open ? (
|
||||
<div data-testid="unsaved-guard" role="alertdialog">
|
||||
<button onClick={onKeepEditing} data-testid="guard-keep">Keep editing</button>
|
||||
<button onClick={onDiscard} data-testid="guard-discard">Discard</button>
|
||||
</div>
|
||||
) : null,
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
storeState = {
|
||||
isPanelOpen: false,
|
||||
isAddFormOpen: false,
|
||||
editingKey: null,
|
||||
closePanel: mockClosePanel,
|
||||
openPanel: mockOpenPanel,
|
||||
fetchSecrets: mockFetchSecrets,
|
||||
};
|
||||
mockClosePanel.mockReset();
|
||||
mockOpenPanel.mockReset();
|
||||
mockFetchSecrets.mockReset().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
// ─── Closed by default ─────────────────────────────────────────────────────
|
||||
|
||||
describe("SettingsPanel — closed by default", () => {
|
||||
it("no dialog content when isPanelOpen=false", () => {
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
// Radix Dialog doesn't render content when open=false
|
||||
expect(screen.queryByTestId("secrets-tab")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Open / close ──────────────────────────────────────────────────────────
|
||||
|
||||
describe("SettingsPanel — open / close", () => {
|
||||
it("renders SecretsTab when panel is open", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-xyz" />);
|
||||
expect(screen.getByTestId("secrets-tab")).toBeTruthy();
|
||||
expect(screen.getByText(/workspaceId=ws-xyz/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders TokensTab tab in tabs list", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
expect(screen.getByRole("tab", { name: /workspace tokens/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders Org API Keys tab in tabs list", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
expect(screen.getByRole("tab", { name: /org api keys/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Secrets tab is default active", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
expect(screen.getByTestId("secrets-tab")).toBeTruthy();
|
||||
expect(screen.getByRole("tab", { name: /secrets/i }).getAttribute("data-state")).toBe("active");
|
||||
});
|
||||
|
||||
it("Tokens tab trigger exists with correct aria attributes", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
const tab = screen.getByRole("tab", { name: /workspace tokens/i });
|
||||
// Radix Tabs.Trigger has role="tab" and aria-selected
|
||||
expect(tab).toBeTruthy();
|
||||
// Secrets tab is active by default
|
||||
const secretsTab = screen.getByRole("tab", { name: /secrets/i });
|
||||
expect(secretsTab.getAttribute("data-state")).toBe("active");
|
||||
// Tokens tab should not be active initially
|
||||
expect(tab.getAttribute("data-state")).not.toBe("active");
|
||||
});
|
||||
|
||||
it("Close button calls closePanel", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /close settings/i }));
|
||||
expect(mockClosePanel).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls fetchSecrets(workspaceId) when panel opens", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-fetch-test" />);
|
||||
expect(mockFetchSecrets).toHaveBeenCalledWith("ws-fetch-test");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Unsaved changes guard ──────────────────────────────────────────────────
|
||||
|
||||
describe("SettingsPanel — unsaved changes guard", () => {
|
||||
it("shows guard when panel closing with isAddFormOpen=true", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
storeState.isAddFormOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /close settings/i }));
|
||||
expect(screen.getByTestId("unsaved-guard")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("guard shows when editingKey is set (dirty form)", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /close settings/i }));
|
||||
expect(screen.getByTestId("unsaved-guard")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("'Keep editing' closes guard but panel stays open", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
storeState.editingKey = "GITHUB_TOKEN";
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
// Trigger close attempt
|
||||
fireEvent.click(screen.getByRole("button", { name: /close settings/i }));
|
||||
expect(screen.getByTestId("unsaved-guard")).toBeTruthy();
|
||||
// Keep editing closes the guard
|
||||
fireEvent.click(screen.getByTestId("guard-keep"));
|
||||
expect(screen.queryByTestId("unsaved-guard")).toBeNull();
|
||||
// Panel content still visible (panel not closed)
|
||||
expect(screen.getByTestId("secrets-tab")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("'Discard' button on guard calls closePanel", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
storeState.isAddFormOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /close settings/i }));
|
||||
fireEvent.click(screen.getByTestId("guard-discard"));
|
||||
expect(mockClosePanel).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Accessibility ──────────────────────────────────────────────────────────
|
||||
|
||||
describe("SettingsPanel — accessibility", () => {
|
||||
it("Dialog.Content has aria-label='Settings: API Keys'", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
expect(document.querySelector('[aria-label="Settings: API Keys"]')).toBeTruthy();
|
||||
});
|
||||
|
||||
it("TabList has aria-label='Settings sections'", () => {
|
||||
storeState.isPanelOpen = true;
|
||||
render(<SettingsPanel workspaceId="ws-1" />);
|
||||
expect(document.querySelector('[aria-label="Settings sections"]')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,312 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* FileEditor — read/edit textarea for workspace config files.
|
||||
*
|
||||
* Covers:
|
||||
* - Empty state (no file selected)
|
||||
* - File header: icon, filename, modified badge
|
||||
* - Textarea renders with correct content
|
||||
* - Save button: disabled when not dirty, enabled when dirty
|
||||
* - Save button: disabled when saving
|
||||
* - Save button: disabled when root !== /configs
|
||||
* - Download button wired
|
||||
* - Tab key inserts 2 spaces (not focus-trapped)
|
||||
* - Cmd+S / Ctrl+S triggers save
|
||||
* - onChange wires setEditContent
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom — use DOM APIs.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import { FileEditor } from "../FileEditor";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const defaultProps = {
|
||||
selectedFile: "/configs/agent.yaml",
|
||||
fileContent: "name: test\nruntime: langgraph",
|
||||
editContent: "name: test\nruntime: langgraph",
|
||||
setEditContent: vi.fn(),
|
||||
loadingFile: false,
|
||||
saving: false,
|
||||
success: null as string | null,
|
||||
root: "/configs",
|
||||
onSave: vi.fn(),
|
||||
onDownload: vi.fn(),
|
||||
};
|
||||
|
||||
// ─── Empty state ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe("FileEditor — empty state", () => {
|
||||
it("renders placeholder when no file is selected", () => {
|
||||
render(<FileEditor {...defaultProps} selectedFile={null} />);
|
||||
expect(document.body.textContent).toContain("Select a file to edit");
|
||||
});
|
||||
|
||||
it("does not render textarea when no file is selected", () => {
|
||||
render(<FileEditor {...defaultProps} selectedFile={null} />);
|
||||
expect(document.querySelector("textarea")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not render save button when no file is selected", () => {
|
||||
render(<FileEditor {...defaultProps} selectedFile={null} />);
|
||||
expect(document.querySelectorAll("button")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── File header ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("FileEditor — file header", () => {
|
||||
beforeEach(() => {
|
||||
defaultProps.setEditContent.mockClear();
|
||||
defaultProps.onSave.mockClear();
|
||||
defaultProps.onDownload.mockClear();
|
||||
});
|
||||
|
||||
it("renders the selected filename in header", () => {
|
||||
render(<FileEditor {...defaultProps} />);
|
||||
expect(document.body.textContent).toContain("/configs/agent.yaml");
|
||||
});
|
||||
|
||||
it("renders an icon (emoji from getIcon)", () => {
|
||||
render(<FileEditor {...defaultProps} selectedFile="/configs/script.py" />);
|
||||
// .py → 🐍 icon
|
||||
const iconSpans = Array.from(document.querySelectorAll("span"));
|
||||
const iconSpan = iconSpans.find((s) => s.textContent === "🐍");
|
||||
expect(iconSpan).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does NOT show modified badge when content is clean", () => {
|
||||
render(
|
||||
<FileEditor
|
||||
{...defaultProps}
|
||||
fileContent="name: test"
|
||||
editContent="name: test"
|
||||
/>,
|
||||
);
|
||||
expect(document.body.textContent).not.toContain("modified");
|
||||
});
|
||||
|
||||
it("shows modified badge when content has been changed", () => {
|
||||
render(
|
||||
<FileEditor
|
||||
{...defaultProps}
|
||||
fileContent="name: test"
|
||||
editContent="name: updated"
|
||||
/>,
|
||||
);
|
||||
expect(document.body.textContent).toContain("modified");
|
||||
});
|
||||
|
||||
it("renders Download button", () => {
|
||||
render(<FileEditor {...defaultProps} />);
|
||||
const dlBtn = document.querySelector('button[aria-label="Download file"]');
|
||||
expect(dlBtn).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders Save button", () => {
|
||||
render(<FileEditor {...defaultProps} />);
|
||||
const saveBtn = Array.from(document.querySelectorAll("button")).find(
|
||||
(b) => b.textContent?.includes("Save"),
|
||||
);
|
||||
expect(saveBtn).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Save button state ────────────────────────────────────────────────────────
|
||||
|
||||
describe("FileEditor — save button state", () => {
|
||||
beforeEach(() => {
|
||||
defaultProps.setEditContent.mockClear();
|
||||
defaultProps.onSave.mockClear();
|
||||
});
|
||||
|
||||
it("Save button is disabled when content is not dirty", () => {
|
||||
render(
|
||||
<FileEditor
|
||||
{...defaultProps}
|
||||
fileContent="name: test"
|
||||
editContent="name: test"
|
||||
/>,
|
||||
);
|
||||
const saveBtn = Array.from(document.querySelectorAll("button")).find(
|
||||
(b) => b.textContent === "Save",
|
||||
);
|
||||
expect(saveBtn?.getAttribute("disabled")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("Save button is enabled when content is dirty", () => {
|
||||
render(
|
||||
<FileEditor
|
||||
{...defaultProps}
|
||||
fileContent="name: test"
|
||||
editContent="name: updated"
|
||||
/>,
|
||||
);
|
||||
const saveBtn = Array.from(document.querySelectorAll("button")).find(
|
||||
(b) => b.textContent === "Save",
|
||||
);
|
||||
expect(saveBtn?.getAttribute("disabled")).toBeNull();
|
||||
});
|
||||
|
||||
it("Save button shows 'Saving...' when saving", () => {
|
||||
render(
|
||||
<FileEditor
|
||||
{...defaultProps}
|
||||
fileContent="name: test"
|
||||
editContent="name: updated"
|
||||
saving={true}
|
||||
/>,
|
||||
);
|
||||
const saveBtn = Array.from(document.querySelectorAll("button")).find(
|
||||
(b) => b.textContent === "Saving...",
|
||||
);
|
||||
expect(saveBtn).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Save button is absent when root is /workspace (not editable)", () => {
|
||||
render(
|
||||
<FileEditor
|
||||
{...defaultProps}
|
||||
root="/workspace"
|
||||
fileContent="name: test"
|
||||
editContent="name: different"
|
||||
/>,
|
||||
);
|
||||
const saveBtn = Array.from(document.querySelectorAll("button")).find(
|
||||
(b) => b.textContent?.includes("Save"),
|
||||
);
|
||||
expect(saveBtn).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Textarea ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("FileEditor — textarea", () => {
|
||||
beforeEach(() => {
|
||||
defaultProps.setEditContent.mockClear();
|
||||
defaultProps.onSave.mockClear();
|
||||
});
|
||||
|
||||
it("renders textarea with the edit content", () => {
|
||||
render(
|
||||
<FileEditor
|
||||
{...defaultProps}
|
||||
editContent="runtime: langgraph"
|
||||
/>,
|
||||
);
|
||||
const ta = document.querySelector("textarea");
|
||||
expect(ta).toBeTruthy();
|
||||
expect(ta?.value).toBe("runtime: langgraph");
|
||||
});
|
||||
|
||||
it("textarea is readOnly when root is not /configs", () => {
|
||||
render(
|
||||
<FileEditor
|
||||
{...defaultProps}
|
||||
root="/workspace"
|
||||
editContent="runtime: langgraph"
|
||||
/>,
|
||||
);
|
||||
const ta = document.querySelector("textarea");
|
||||
expect(ta?.readOnly).toBe(true);
|
||||
});
|
||||
|
||||
it("textarea is editable when root is /configs", () => {
|
||||
render(
|
||||
<FileEditor
|
||||
{...defaultProps}
|
||||
root="/configs"
|
||||
editContent="runtime: langgraph"
|
||||
/>,
|
||||
);
|
||||
const ta = document.querySelector("textarea");
|
||||
expect(ta?.readOnly).toBe(false);
|
||||
});
|
||||
|
||||
it("onChange is called when textarea content changes", () => {
|
||||
render(<FileEditor {...defaultProps} />);
|
||||
const ta = document.querySelector("textarea")!;
|
||||
fireEvent.change(ta, { target: { value: "new content" } });
|
||||
expect(defaultProps.setEditContent).toHaveBeenCalledWith("new content");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Keyboard shortcuts ──────────────────────────────────────────────────────
|
||||
|
||||
describe("FileEditor — keyboard shortcuts", () => {
|
||||
beforeEach(() => {
|
||||
defaultProps.setEditContent.mockClear();
|
||||
defaultProps.onSave.mockClear();
|
||||
});
|
||||
|
||||
it("Tab key handler does not crash on textarea", () => {
|
||||
// Tab key handling requires DOM selection state that fireEvent doesn't
|
||||
// reliably propagate to React refs in jsdom. Verify the textarea
|
||||
// renders without crashing when Tab is pressed.
|
||||
render(
|
||||
<FileEditor
|
||||
{...defaultProps}
|
||||
editContent="line1\ncursor"
|
||||
/>,
|
||||
);
|
||||
const ta = document.querySelector("textarea") as HTMLTextAreaElement;
|
||||
// Should not throw
|
||||
expect(() => fireEvent.keyDown(ta, { key: "Tab" })).not.toThrow();
|
||||
});
|
||||
|
||||
it("Ctrl+S (or Meta+S) triggers onSave", () => {
|
||||
// Test the handler directly — fireEvent doesn't carry ctrlKey/metaKey
|
||||
// through the React onKeyDown bridge reliably in jsdom.
|
||||
// We verify the component wires the handler and that the handler
|
||||
// exists by calling it with a correctly-shaped synthetic event.
|
||||
render(<FileEditor {...defaultProps} />);
|
||||
const ta = document.querySelector("textarea")!;
|
||||
// Directly invoke the component's onKeyDown with the right modifier keys
|
||||
fireEvent.keyDown(ta, { key: "s", ctrlKey: true, metaKey: false });
|
||||
// The component checks (e.metaKey || e.ctrlKey) — with ctrlKey=true
|
||||
// this should call onSave
|
||||
expect(defaultProps.onSave).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("Ctrl+S does NOT trigger onSave when key is not 's'", () => {
|
||||
render(<FileEditor {...defaultProps} />);
|
||||
const ta = document.querySelector("textarea")!;
|
||||
fireEvent.keyDown(ta, { key: "a", ctrlKey: true });
|
||||
expect(defaultProps.onSave).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Loading state ───────────────────────────────────────────────────────────
|
||||
|
||||
describe("FileEditor — loading state", () => {
|
||||
it("shows loading text when loadingFile=true", () => {
|
||||
render(
|
||||
<FileEditor {...defaultProps} loadingFile={true} />,
|
||||
);
|
||||
expect(document.body.textContent).toContain("Loading...");
|
||||
});
|
||||
|
||||
it("does not render textarea while loading", () => {
|
||||
render(
|
||||
<FileEditor {...defaultProps} loadingFile={true} />,
|
||||
);
|
||||
expect(document.querySelector("textarea")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Success message ─────────────────────────────────────────────────────────
|
||||
|
||||
describe("FileEditor — success message", () => {
|
||||
it("shows success message when provided", () => {
|
||||
render(
|
||||
<FileEditor {...defaultProps} success="Saved!" />,
|
||||
);
|
||||
expect(document.body.textContent).toContain("Saved!");
|
||||
});
|
||||
});
|
||||
@@ -1,349 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for FilesToolbar — the top-of-panel bar for the Files tab.
|
||||
* Covers: directory select, file count, New/Upload/Clear (configs-only),
|
||||
* Export, Refresh, and aria-labels.
|
||||
*/
|
||||
import React from "react";
|
||||
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { FilesToolbar } from "../FilesToolbar";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("FilesToolbar", () => {
|
||||
describe("renders base toolbar", () => {
|
||||
it("renders the directory select with aria-label", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={3}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(
|
||||
screen.getByRole("combobox", { name: /file root directory/i })
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders the file count", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={7}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByText("7 files")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders Export button", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={0}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(
|
||||
screen.getByRole("button", { name: /download all files/i })
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders Refresh button", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={0}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByRole("button", { name: /refresh file list/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders 0 files when count is 0", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={0}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByText("0 files")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("configs-only buttons", () => {
|
||||
it("shows New and Upload buttons when root is /configs", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={3}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(
|
||||
screen.getByRole("button", { name: /create new file/i })
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
screen.getByRole("button", { name: /upload folder/i })
|
||||
).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /delete all files/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("hides New and Upload when root is /workspace", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/workspace"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={5}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /create new file/i })
|
||||
).toBeNull();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /upload folder/i })
|
||||
).toBeNull();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /delete all files/i })
|
||||
).toBeNull();
|
||||
// Export and Refresh are still present
|
||||
expect(
|
||||
screen.getByRole("button", { name: /download all files/i })
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("hides New and Upload when root is /home", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/home"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={2}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /create new file/i })
|
||||
).toBeNull();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /upload folder/i })
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("hides New and Upload when root is /plugins", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/plugins"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={1}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /create new file/i })
|
||||
).toBeNull();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /upload folder/i })
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("callbacks", () => {
|
||||
it("calls setRoot when directory is changed", () => {
|
||||
const setRoot = vi.fn();
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={setRoot}
|
||||
fileCount={3}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
fireEvent.change(screen.getByRole("combobox"), {
|
||||
target: { value: "/workspace" },
|
||||
});
|
||||
expect(setRoot).toHaveBeenCalledWith("/workspace");
|
||||
});
|
||||
|
||||
it("calls onNewFile when New button is clicked", () => {
|
||||
const onNewFile = vi.fn();
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={3}
|
||||
onNewFile={onNewFile}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: /create new file/i }));
|
||||
expect(onNewFile).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onDownloadAll when Export button is clicked", () => {
|
||||
const onDownloadAll = vi.fn();
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/workspace"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={5}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={onDownloadAll}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: /download all files/i }));
|
||||
expect(onDownloadAll).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onClearAll when Clear button is clicked", () => {
|
||||
const onClearAll = vi.fn();
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={3}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={onClearAll}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: /delete all files/i }));
|
||||
expect(onClearAll).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onRefresh when Refresh button is clicked", () => {
|
||||
const onRefresh = vi.fn();
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={3}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={onRefresh}
|
||||
/>
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: /refresh file list/i }));
|
||||
expect(onRefresh).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onUpload when the hidden file input changes", () => {
|
||||
const onUpload = vi.fn();
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={3}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={onUpload}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
// Find the hidden file input
|
||||
const fileInput = document.querySelector(
|
||||
'input[type="file"]'
|
||||
) as HTMLInputElement;
|
||||
expect(fileInput).toBeTruthy();
|
||||
expect(fileInput?.getAttribute("aria-label")).toBe("Upload folder files");
|
||||
});
|
||||
});
|
||||
|
||||
describe("a11y", () => {
|
||||
it("all buttons have aria-label or accessible name", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={3}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
// All buttons should be findable by role
|
||||
const buttons = screen.getAllByRole("button");
|
||||
for (const btn of buttons) {
|
||||
expect(btn.getAttribute("aria-label") ?? btn.textContent).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it("directory select has aria-label", () => {
|
||||
render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={vi.fn()}
|
||||
fileCount={3}
|
||||
onNewFile={vi.fn()}
|
||||
onUpload={vi.fn()}
|
||||
onDownloadAll={vi.fn()}
|
||||
onClearAll={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
);
|
||||
const select = screen.getByRole("combobox");
|
||||
expect(select.getAttribute("aria-label")).toBe("File root directory");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,101 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for NotAvailablePanel — the full-tab placeholder shown when a
|
||||
* workspace's runtime doesn't own a platform-managed filesystem (today:
|
||||
* runtime === "external"). Covers rendering, a11y, and runtime prop
|
||||
* display.
|
||||
*/
|
||||
import React from "react";
|
||||
import { render, screen, cleanup } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { NotAvailablePanel } from "../NotAvailablePanel";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("NotAvailablePanel", () => {
|
||||
describe("renders", () => {
|
||||
it("renders the heading", () => {
|
||||
render(<NotAvailablePanel runtime="external" />);
|
||||
expect(screen.getByText("Files not available")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders the description text", () => {
|
||||
render(<NotAvailablePanel runtime="external" />);
|
||||
expect(
|
||||
screen.getByText(/whose filesystem isn't owned by the platform/i)
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("displays the runtime name in the description", () => {
|
||||
render(<NotAvailablePanel runtime="aws-lambda" />);
|
||||
// The runtime name appears inside the paragraph
|
||||
const para = screen.getByText(/whose filesystem isn't owned/i);
|
||||
expect(para.textContent).toContain("aws-lambda");
|
||||
});
|
||||
|
||||
it("renders the SVG folder icon with aria-hidden", () => {
|
||||
render(<NotAvailablePanel runtime="external" />);
|
||||
const svg = document.querySelector("svg");
|
||||
expect(svg).toBeTruthy();
|
||||
expect(svg?.getAttribute("aria-hidden")).toBe("true");
|
||||
});
|
||||
|
||||
it("uses the provided runtime prop verbatim", () => {
|
||||
render(<NotAvailablePanel runtime="cloud-run" />);
|
||||
const monoRuntime = document.querySelector(".font-mono");
|
||||
expect(monoRuntime?.textContent).toBe("cloud-run");
|
||||
});
|
||||
|
||||
it("renders the 'Use the Chat tab' guidance text", () => {
|
||||
render(<NotAvailablePanel runtime="external" />);
|
||||
expect(screen.getByText(/Use the Chat tab/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("is contained in a full-height flex column", () => {
|
||||
render(<NotAvailablePanel runtime="external" />);
|
||||
const container = screen.getByText("Files not available").closest("div");
|
||||
expect(container?.className).toContain("flex");
|
||||
expect(container?.className).toContain("flex-col");
|
||||
expect(container?.className).toContain("items-center");
|
||||
expect(container?.className).toContain("justify-center");
|
||||
expect(container?.className).toContain("h-full");
|
||||
});
|
||||
});
|
||||
|
||||
describe("a11y", () => {
|
||||
it("heading is an h3", () => {
|
||||
render(<NotAvailablePanel runtime="external" />);
|
||||
expect(screen.getByRole("heading", { level: 3 })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("SVG icon has aria-hidden so screen readers skip it", () => {
|
||||
render(<NotAvailablePanel runtime="external" />);
|
||||
const svg = document.querySelector("svg");
|
||||
expect(svg?.getAttribute("aria-hidden")).toBe("true");
|
||||
});
|
||||
|
||||
it("description paragraph is present with descriptive text", () => {
|
||||
render(<NotAvailablePanel runtime="external" />);
|
||||
const paras = document.querySelectorAll("p");
|
||||
expect(paras.length).toBeGreaterThan(0);
|
||||
const text = Array.from(paras)
|
||||
.map((p) => p.textContent)
|
||||
.join(" ");
|
||||
expect(text.toLowerCase()).toContain("runtime");
|
||||
});
|
||||
});
|
||||
|
||||
describe("props", () => {
|
||||
it("renders with a short runtime name", () => {
|
||||
render(<NotAvailablePanel runtime="ext" />);
|
||||
const monoRuntime = document.querySelector(".font-mono");
|
||||
expect(monoRuntime?.textContent).toBe("ext");
|
||||
});
|
||||
|
||||
it("renders with a complex runtime name", () => {
|
||||
render(<NotAvailablePanel runtime="gcp-cloud-functions-v2" />);
|
||||
const monoRuntime = document.querySelector(".font-mono");
|
||||
expect(monoRuntime?.textContent).toBe("gcp-cloud-functions-v2");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,96 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* useFilesApi.ts — walkEntry coverage only.
|
||||
*
|
||||
* The __testables import pulls in the full useFilesApi.ts module (355 lines,
|
||||
* imports react, @/lib/api, @/store/canvas). In the jsdom pool this can
|
||||
* OOM on complex mocks. Only the lightweight walkEntry file cases are
|
||||
* tested here.
|
||||
*
|
||||
* Covers:
|
||||
* - walkEntry: file entry resolves with correct path and content
|
||||
* - walkEntry: prefix handling
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom — use DOM APIs.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { __testables } from "../useFilesApi";
|
||||
|
||||
const { walkEntry } = __testables;
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
interface CollectedEntry {
|
||||
file: File;
|
||||
relativePath: string;
|
||||
}
|
||||
|
||||
function makeFile(name: string, content = "test content"): { entry: object; file: File } {
|
||||
const file = new File([content], name, { type: "text/plain" });
|
||||
const entry = {
|
||||
isFile: true,
|
||||
isDirectory: false,
|
||||
name,
|
||||
fullPath: "/" + name,
|
||||
file: (success: (f: File) => void) => success(file),
|
||||
};
|
||||
return { entry: entry as never, file };
|
||||
}
|
||||
|
||||
// ─── walkEntry — file entries ─────────────────────────────────────────────────
|
||||
|
||||
describe("walkEntry — file entry", () => {
|
||||
it("resolves a file entry with its relative path", async () => {
|
||||
const { entry } = makeFile("notes.md", "hello world");
|
||||
const out: CollectedEntry[] = [];
|
||||
await walkEntry(entry as never, "", out);
|
||||
expect(out).toHaveLength(1);
|
||||
expect(out[0]!.relativePath).toBe("notes.md");
|
||||
expect(await out[0]!.file.text()).toBe("hello world");
|
||||
});
|
||||
|
||||
it("uses the provided prefix in the relative path", async () => {
|
||||
const { entry } = makeFile("README.md");
|
||||
const out: CollectedEntry[] = [];
|
||||
await walkEntry(entry as never, "docs", out);
|
||||
expect(out[0]!.relativePath).toBe("docs/README.md");
|
||||
});
|
||||
|
||||
it("preserves nested prefixes across calls", async () => {
|
||||
const { entry } = makeFile("index.ts");
|
||||
const out: CollectedEntry[] = [];
|
||||
await walkEntry(entry as never, "src/components", out);
|
||||
expect(out[0]!.relativePath).toBe("src/components/index.ts");
|
||||
});
|
||||
|
||||
it("handles filenames with spaces", async () => {
|
||||
const { entry } = makeFile("my notes.txt", "content");
|
||||
const out: CollectedEntry[] = [];
|
||||
await walkEntry(entry as never, "", out);
|
||||
expect(out[0]!.relativePath).toBe("my notes.txt");
|
||||
});
|
||||
|
||||
it("handles filenames with unicode", async () => {
|
||||
const { entry } = makeFile("日本語.txt", "data");
|
||||
const out: CollectedEntry[] = [];
|
||||
await walkEntry(entry as never, "", out);
|
||||
expect(out[0]!.relativePath).toBe("日本語.txt");
|
||||
});
|
||||
|
||||
it("populates the File object with correct content", async () => {
|
||||
const { entry, file } = makeFile("config.yaml", "runtime: langgraph");
|
||||
const out: CollectedEntry[] = [];
|
||||
await walkEntry(entry as never, "", out);
|
||||
expect(out[0]!.file).toBe(file);
|
||||
expect(await out[0]!.file.text()).toBe("runtime: langgraph");
|
||||
});
|
||||
|
||||
it("appends to existing entries array (non-destructive)", async () => {
|
||||
const { entry } = makeFile("extra.ts");
|
||||
const out: CollectedEntry[] = [{ file: new File(["preexisting"], "prev.ts"), relativePath: "prev.ts" }];
|
||||
await walkEntry(entry as never, "", out);
|
||||
expect(out).toHaveLength(2);
|
||||
expect(out[0]!.relativePath).toBe("prev.ts");
|
||||
expect(out[1]!.relativePath).toBe("extra.ts");
|
||||
});
|
||||
});
|
||||
@@ -1,160 +0,0 @@
|
||||
// @vitest-environment node
|
||||
/**
|
||||
* FilesTab tree utilities — pure function coverage.
|
||||
*
|
||||
* Covers:
|
||||
* - getIcon: case-insensitive extension lookup, directory icons, unknown extensions
|
||||
* - buildTree: flat list → nested tree, dirs-first sorting, duplicate dir guard,
|
||||
* nested paths, single-level files
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildTree, getIcon, type FileEntry } from "./tree";
|
||||
|
||||
// ─── getIcon ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("getIcon — directory", () => {
|
||||
it("returns folder icon for directories", () => {
|
||||
expect(getIcon("src", true)).toBe("📁");
|
||||
expect(getIcon("src/components", true)).toBe("📁");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getIcon — extension mapping", () => {
|
||||
const cases: [string, string][] = [
|
||||
// Known extensions
|
||||
["script.py", "🐍"],
|
||||
["script.PY", "🐍"], // case-insensitive
|
||||
["script.Py", "🐍"],
|
||||
["main.ts", "💠"],
|
||||
["main.TS", "💠"],
|
||||
["component.tsx", "💠"],
|
||||
["style.css", "🎨"],
|
||||
["index.html", "🌐"],
|
||||
["data.json", "{}"],
|
||||
["app.js", "📜"],
|
||||
["config.yaml", "⚙"],
|
||||
["config.yml", "⚙"],
|
||||
["README.md", "📄"],
|
||||
["build.sh", "▸"],
|
||||
// Unknown extension → default
|
||||
["photo.png", "📄"],
|
||||
["archive.zip", "📄"],
|
||||
["document.pdf", "📄"],
|
||||
["data.xml", "📄"],
|
||||
];
|
||||
|
||||
it.each(cases)("getIcon('%s', false) === '%s'", (path, expected) => {
|
||||
expect(getIcon(path, false)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getIcon — edge cases", () => {
|
||||
it("no extension (dotfile) falls back to default", () => {
|
||||
expect(getIcon(".gitignore", false)).toBe("📄");
|
||||
expect(getIcon(".env.local", false)).toBe("📄");
|
||||
});
|
||||
|
||||
it("single-component path with no extension falls back to default", () => {
|
||||
expect(getIcon("Makefile", false)).toBe("📄");
|
||||
});
|
||||
|
||||
it("double extension takes last segment as extension", () => {
|
||||
// "file.min.js" → ext = ".js" → 📜 (JS icon)
|
||||
expect(getIcon("file.min.js", false)).toBe("📜");
|
||||
// "app.d.ts" → ext = ".ts" → 💠 (TS icon)
|
||||
expect(getIcon("app.d.ts", false)).toBe("💠");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── buildTree ──────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("buildTree — empty input", () => {
|
||||
it("returns empty array for empty input", () => {
|
||||
expect(buildTree([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildTree — flat files", () => {
|
||||
it("puts files at root level", () => {
|
||||
const files: FileEntry[] = [
|
||||
{ path: "a.txt", size: 10, dir: false },
|
||||
{ path: "b.txt", size: 20, dir: false },
|
||||
];
|
||||
const tree = buildTree(files);
|
||||
expect(tree).toHaveLength(2);
|
||||
expect(tree[0]!.name).toBe("a.txt");
|
||||
expect(tree[0]!.path).toBe("a.txt");
|
||||
expect(tree[0]!.isDir).toBe(false);
|
||||
expect(tree[0]!.size).toBe(10);
|
||||
});
|
||||
|
||||
it("directories appear before files (dirs-first)", () => {
|
||||
const files: FileEntry[] = [
|
||||
{ path: "b.txt", size: 10, dir: false },
|
||||
{ path: "src", size: 0, dir: true },
|
||||
{ path: "a.txt", size: 10, dir: false },
|
||||
];
|
||||
const tree = buildTree(files);
|
||||
expect(tree[0]!.isDir).toBe(true);
|
||||
expect(tree[0]!.name).toBe("src");
|
||||
expect(tree[1]!.name).toBe("a.txt");
|
||||
expect(tree[2]!.name).toBe("b.txt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildTree — nested paths", () => {
|
||||
it("builds correct nested structure", () => {
|
||||
const files: FileEntry[] = [
|
||||
{ path: "src", size: 0, dir: true },
|
||||
{ path: "src/app.tsx", size: 100, dir: false },
|
||||
{ path: "src/app.css", size: 50, dir: false },
|
||||
];
|
||||
const tree = buildTree(files);
|
||||
expect(tree).toHaveLength(1);
|
||||
expect(tree[0]!.name).toBe("src");
|
||||
expect(tree[0]!.isDir).toBe(true);
|
||||
expect(tree[0]!.children).toHaveLength(2);
|
||||
expect(tree[0]!.children[0]!.name).toBe("app.css");
|
||||
expect(tree[0]!.children[1]!.name).toBe("app.tsx");
|
||||
});
|
||||
|
||||
it("deeply nested paths build correct depth", () => {
|
||||
const files: FileEntry[] = [
|
||||
{ path: "a", size: 0, dir: true },
|
||||
{ path: "a/b", size: 0, dir: true },
|
||||
{ path: "a/b/c.txt", size: 30, dir: false },
|
||||
];
|
||||
const tree = buildTree(files);
|
||||
expect(tree[0]!.name).toBe("a");
|
||||
expect(tree[0]!.children[0]!.name).toBe("b");
|
||||
expect(tree[0]!.children[0]!.children[0]!.name).toBe("c.txt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildTree — duplicate dir guard", () => {
|
||||
it("ignores duplicate directory entries", () => {
|
||||
const files: FileEntry[] = [
|
||||
{ path: "src", size: 0, dir: true },
|
||||
{ path: "src", size: 0, dir: true }, // duplicate
|
||||
{ path: "src/app.ts", size: 10, dir: false },
|
||||
];
|
||||
const tree = buildTree(files);
|
||||
// Should only create src node once
|
||||
const src = tree.find((n) => n.name === "src");
|
||||
expect(src).toBeDefined();
|
||||
expect(src!.children).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildTree — alphabetical sort within same level", () => {
|
||||
it("sorts alphabetically at each level", () => {
|
||||
const files: FileEntry[] = [
|
||||
{ path: "zebra.txt", size: 1, dir: false },
|
||||
{ path: "apple.txt", size: 1, dir: false },
|
||||
{ path: "banana.txt", size: 1, dir: false },
|
||||
];
|
||||
const tree = buildTree(files);
|
||||
expect(tree.map((n) => n.name)).toEqual(["apple.txt", "banana.txt", "zebra.txt"]);
|
||||
});
|
||||
});
|
||||
@@ -1,247 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* AttachmentLightbox — fullscreen modal for image / PDF preview.
|
||||
*
|
||||
* Owns: backdrop + viewport, Esc to close, click-outside to close,
|
||||
* focus trap (close button focus on open, restore on close),
|
||||
* prefers-reduced-motion respect.
|
||||
*
|
||||
* Coverage:
|
||||
* - Null when open=false
|
||||
* - Renders dialog with correct ARIA roles and label when open
|
||||
* - Close button present and wired
|
||||
* - Focus moves to close button on open
|
||||
* - Focus restores to previous element on close
|
||||
* - Esc key closes via document listener
|
||||
* - Click outside closes
|
||||
* - Click on content does NOT close (stopPropagation)
|
||||
* - Cleanup removes document listener on unmount
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom — use DOM APIs.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import { AttachmentLightbox } from "../AttachmentLightbox";
|
||||
|
||||
// ─── Mock children ─────────────────────────────────────────────────────────────
|
||||
|
||||
const MockContent = ({ onClick }: { onClick?: () => void }) => (
|
||||
<img
|
||||
src="file:///test.png"
|
||||
alt="test preview"
|
||||
onClick={onClick}
|
||||
data-testid="lightbox-content"
|
||||
/>
|
||||
);
|
||||
|
||||
// ─── Setup / teardown ─────────────────────────────────────────────────────────
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
// ─── Render ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentLightbox — render", () => {
|
||||
it("renders nothing when open=false", () => {
|
||||
render(
|
||||
<AttachmentLightbox
|
||||
open={false}
|
||||
onClose={vi.fn()}
|
||||
ariaLabel="Preview image"
|
||||
>
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
expect(dialog).toBeNull();
|
||||
});
|
||||
|
||||
it("renders dialog with role=dialog when open", () => {
|
||||
render(
|
||||
<AttachmentLightbox
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
ariaLabel="Preview image"
|
||||
>
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
expect(dialog).toBeTruthy();
|
||||
});
|
||||
|
||||
it("sets aria-modal=true on dialog", () => {
|
||||
render(
|
||||
<AttachmentLightbox
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
ariaLabel="Preview image"
|
||||
>
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
expect(dialog?.getAttribute("aria-modal")).toBe("true");
|
||||
});
|
||||
|
||||
it("applies aria-label to dialog", () => {
|
||||
render(
|
||||
<AttachmentLightbox
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
ariaLabel="Preview image: photo.png"
|
||||
>
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
expect(dialog?.getAttribute("aria-label")).toBe("Preview image: photo.png");
|
||||
});
|
||||
|
||||
it("renders children inside the dialog", () => {
|
||||
render(
|
||||
<AttachmentLightbox
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
ariaLabel="Preview"
|
||||
>
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
const img = document.querySelector("img");
|
||||
expect(img).toBeTruthy();
|
||||
expect(img?.getAttribute("alt")).toBe("test preview");
|
||||
});
|
||||
|
||||
it("renders close button with correct aria-label", () => {
|
||||
render(
|
||||
<AttachmentLightbox
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
ariaLabel="Preview"
|
||||
>
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
const closeBtn = document.querySelector('button[aria-label="Close preview"]');
|
||||
expect(closeBtn).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Focus management ─────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentLightbox — focus management", () => {
|
||||
it("focuses the close button when opened", () => {
|
||||
const onClose = vi.fn();
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview">
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
// Advance timers so the useEffect runs (it uses setTimeout 0 internally)
|
||||
vi.advanceTimersByTime(0);
|
||||
const closeBtn = document.querySelector('button[aria-label="Close preview"]');
|
||||
expect(closeBtn).toBe(document.activeElement);
|
||||
});
|
||||
|
||||
it("calls onClose when close button is clicked", () => {
|
||||
const onClose = vi.fn();
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview">
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
vi.advanceTimersByTime(0);
|
||||
const closeBtn = document.querySelector('button[aria-label="Close preview"]')!;
|
||||
fireEvent.click(closeBtn);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Keyboard interaction ──────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentLightbox — keyboard", () => {
|
||||
it("calls onClose when Escape is pressed", () => {
|
||||
const onClose = vi.fn();
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview">
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
vi.advanceTimersByTime(0);
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not call onClose for non-Escape keys", () => {
|
||||
const onClose = vi.fn();
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview">
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
vi.advanceTimersByTime(0);
|
||||
fireEvent.keyDown(document, { key: "Enter" });
|
||||
fireEvent.keyDown(document, { key: " " });
|
||||
fireEvent.keyDown(document, { key: "a" });
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Click interaction ────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentLightbox — click", () => {
|
||||
it("calls onClose when clicking the backdrop (outer div)", () => {
|
||||
const onClose = vi.fn();
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview">
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
vi.advanceTimersByTime(0);
|
||||
const dialog = document.querySelector('[role="dialog"]')!;
|
||||
fireEvent.click(dialog);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does NOT call onClose when clicking the content area (stopPropagation)", () => {
|
||||
const onClose = vi.fn();
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview">
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
vi.advanceTimersByTime(0);
|
||||
const content = document.querySelector('[data-testid="lightbox-content"]');
|
||||
expect(content).toBeTruthy();
|
||||
fireEvent.click(content!);
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Cleanup ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentLightbox — cleanup", () => {
|
||||
it("removes document keydown listener on unmount", () => {
|
||||
const onClose = vi.fn();
|
||||
const { unmount } = render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview">
|
||||
<MockContent />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
vi.advanceTimersByTime(0);
|
||||
unmount();
|
||||
// After unmount, keyDown should not call onClose (listener removed)
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,245 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* TestConnectionButton — async connection tester for secret keys.
|
||||
*
|
||||
* States: idle → testing → success/failure → auto-reset to idle.
|
||||
*
|
||||
* Coverage:
|
||||
* - Idle state: renders "Test connection" label
|
||||
* - Disabled when secretValue is empty
|
||||
* - Enabled when secretValue is present
|
||||
* - Disabled while testing
|
||||
* - Success path: calls validateSecret, shows "Connected ✓", resets after 3s
|
||||
* - Failure path: calls validateSecret, shows "Test failed", shows error detail
|
||||
* - Catch path: network error shows "Connection timed out"
|
||||
* - Error detail only shown on failure state
|
||||
* - onResult callback called with correct value
|
||||
* - Cleanup: timer cancelled on unmount
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom — use DOM APIs.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import { TestConnectionButton } from "../TestConnectionButton";
|
||||
|
||||
const mockValidateSecret = vi.fn();
|
||||
|
||||
vi.mock("@/lib/api/secrets", () => ({
|
||||
validateSecret: (...args: unknown[]) => mockValidateSecret(...args),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("TestConnectionButton — render", () => {
|
||||
it("renders 'Test connection' in idle state", () => {
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_xxx" />,
|
||||
);
|
||||
expect(document.body.textContent).toContain("Test connection");
|
||||
});
|
||||
|
||||
it("is disabled when secretValue is empty", () => {
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="" />,
|
||||
);
|
||||
const btn = document.querySelector('button[type="button"]');
|
||||
expect(btn?.getAttribute("disabled")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("is enabled when secretValue is present", () => {
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_xxx" />,
|
||||
);
|
||||
const btn = document.querySelector('button[type="button"]');
|
||||
expect(btn?.getAttribute("disabled")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("TestConnectionButton — success path", () => {
|
||||
it("shows 'Testing…' while validating", async () => {
|
||||
mockValidateSecret.mockImplementation(
|
||||
() => new Promise(() => {}), // never resolves — stays in testing state
|
||||
);
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_xxx" />,
|
||||
);
|
||||
const btn = document.querySelector('button[type="button"]')!;
|
||||
await act(async () => {
|
||||
fireEvent.click(btn);
|
||||
});
|
||||
|
||||
expect(document.body.textContent).toContain("Testing");
|
||||
expect(btn.getAttribute("disabled")).not.toBeNull(); // disabled while testing
|
||||
});
|
||||
|
||||
it("shows 'Connected ✓' after successful validation", async () => {
|
||||
mockValidateSecret.mockResolvedValue({ valid: true });
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_xxx" />,
|
||||
);
|
||||
const btn = document.querySelector('button[type="button"]')!;
|
||||
fireEvent.click(btn);
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
expect(document.body.textContent).toContain("Connected");
|
||||
});
|
||||
|
||||
it("resets to idle after 3 seconds on success", async () => {
|
||||
mockValidateSecret.mockResolvedValue({ valid: true });
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_xxx" />,
|
||||
);
|
||||
fireEvent.click(document.querySelector('button[type="button"]')!);
|
||||
|
||||
// Resolve the mock and flush React state synchronously via act
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
|
||||
// Advance past the 3000ms RESET_DELAYS.success
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(3001);
|
||||
});
|
||||
expect(document.body.textContent).toContain("Test connection");
|
||||
});
|
||||
|
||||
it("calls onResult(true) on success", async () => {
|
||||
const onResult = vi.fn();
|
||||
mockValidateSecret.mockResolvedValue({ valid: true });
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_xxx" onResult={onResult} />,
|
||||
);
|
||||
fireEvent.click(document.querySelector('button[type="button"]')!);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
expect(onResult).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("TestConnectionButton — failure path", () => {
|
||||
it("shows 'Test failed' after invalid key", async () => {
|
||||
mockValidateSecret.mockResolvedValue({ valid: false, error: "Invalid token" });
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_invalid" />,
|
||||
);
|
||||
fireEvent.click(document.querySelector('button[type="button"]')!);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
expect(document.body.textContent).toContain("Test failed");
|
||||
});
|
||||
|
||||
it("shows error detail message", async () => {
|
||||
mockValidateSecret.mockResolvedValue({
|
||||
valid: false,
|
||||
error: "Token missing required scopes",
|
||||
});
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_invalid" />,
|
||||
);
|
||||
fireEvent.click(document.querySelector('button[type="button"]')!);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
expect(document.body.textContent).toContain("Token missing required scopes");
|
||||
});
|
||||
|
||||
it("resets to idle after 5 seconds on failure", async () => {
|
||||
mockValidateSecret.mockResolvedValue({ valid: false });
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_invalid" />,
|
||||
);
|
||||
fireEvent.click(document.querySelector('button[type="button"]')!);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(5001);
|
||||
});
|
||||
expect(document.body.textContent).toContain("Test connection");
|
||||
});
|
||||
|
||||
it("shows default error when error is absent", async () => {
|
||||
mockValidateSecret.mockResolvedValue({ valid: false });
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_invalid" />,
|
||||
);
|
||||
fireEvent.click(document.querySelector('button[type="button"]')!);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
expect(document.body.textContent).toContain("Could not verify key");
|
||||
});
|
||||
|
||||
it("calls onResult(false) on failure", async () => {
|
||||
const onResult = vi.fn();
|
||||
mockValidateSecret.mockResolvedValue({ valid: false });
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_invalid" onResult={onResult} />,
|
||||
);
|
||||
fireEvent.click(document.querySelector('button[type="button"]')!);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
expect(onResult).toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("TestConnectionButton — catch path", () => {
|
||||
it("shows 'Connection timed out' on network error", async () => {
|
||||
mockValidateSecret.mockRejectedValue(new Error("timeout"));
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_xxx" />,
|
||||
);
|
||||
fireEvent.click(document.querySelector('button[type="button"]')!);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
expect(document.body.textContent).toContain("Connection timed out");
|
||||
});
|
||||
|
||||
it("calls onResult(false) on network error", async () => {
|
||||
const onResult = vi.fn();
|
||||
mockValidateSecret.mockRejectedValue(new Error("timeout"));
|
||||
render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_xxx" onResult={onResult} />,
|
||||
);
|
||||
fireEvent.click(document.querySelector('button[type="button"]')!);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
expect(onResult).toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("TestConnectionButton — cleanup", () => {
|
||||
it("clears timer on unmount", async () => {
|
||||
const clearTimeoutSpy = vi.spyOn(globalThis, "clearTimeout");
|
||||
mockValidateSecret.mockImplementation(
|
||||
() => new Promise(() => {}), // never resolves
|
||||
);
|
||||
const { unmount } = render(
|
||||
<TestConnectionButton provider="github" secretValue="ghp_xxx" />,
|
||||
);
|
||||
await act(async () => {
|
||||
fireEvent.click(document.querySelector('button[type="button"]')!);
|
||||
});
|
||||
unmount();
|
||||
expect(clearTimeoutSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,88 +0,0 @@
|
||||
# Gitea Merge Queue
|
||||
|
||||
Gitea 1.22.6 does not provide a real merge queue. Its `pull_auto_merge`
|
||||
table is auto-merge-on-green, not a serialized queue that retests each PR
|
||||
against the latest `main`.
|
||||
|
||||
`gitea-merge-queue` is the external queue for `molecule-core`.
|
||||
|
||||
## Queue Contract
|
||||
|
||||
Add the `merge-queue` label to an open PR when it is ready to merge.
|
||||
|
||||
The bot processes one PR per tick:
|
||||
|
||||
1. Confirms `main` is green.
|
||||
2. Selects the oldest open PR carrying `merge-queue`.
|
||||
3. Skips PRs with `merge-queue-hold`.
|
||||
4. Rejects fork PRs because the queue may only update same-repo branches.
|
||||
5. If the PR head does not contain current `main`, calls Gitea's
|
||||
`/pulls/{n}/update?style=merge` endpoint and waits for CI on the new head.
|
||||
6. Merges only after the current PR head has required contexts green:
|
||||
- `CI / all-required (pull_request)`
|
||||
- `sop-checklist / all-items-acked (pull_request)`
|
||||
|
||||
The workflow is serialized with `concurrency`, so two queued PRs cannot be
|
||||
merged against the same observed `main`.
|
||||
|
||||
## Operator Commands
|
||||
|
||||
Queue a PR:
|
||||
|
||||
```bash
|
||||
curl -fsS -X POST \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
"https://git.moleculesai.app/api/v1/repos/molecule-ai/molecule-core/issues/<PR>/labels" \
|
||||
-d '{"labels":["merge-queue"]}'
|
||||
```
|
||||
|
||||
Temporarily hold a queued PR:
|
||||
|
||||
```bash
|
||||
curl -fsS -X POST \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
"https://git.moleculesai.app/api/v1/repos/molecule-ai/molecule-core/issues/<PR>/labels" \
|
||||
-d '{"labels":["merge-queue-hold"]}'
|
||||
```
|
||||
|
||||
Run the bot manually from a trusted checkout:
|
||||
|
||||
```bash
|
||||
GITEA_TOKEN="$DEVOPS_ENGINEER_TOKEN" \
|
||||
GITEA_HOST=git.moleculesai.app \
|
||||
REPO=molecule-ai/molecule-core \
|
||||
WATCH_BRANCH=main \
|
||||
QUEUE_LABEL=merge-queue \
|
||||
HOLD_LABEL=merge-queue-hold \
|
||||
UPDATE_STYLE=merge \
|
||||
REQUIRED_CONTEXTS='CI / all-required (pull_request),sop-checklist / all-items-acked (pull_request)' \
|
||||
python3 .gitea/scripts/gitea-merge-queue.py
|
||||
```
|
||||
|
||||
Dry run:
|
||||
|
||||
```bash
|
||||
python3 .gitea/scripts/gitea-merge-queue.py --dry-run
|
||||
```
|
||||
|
||||
## Branch Protection
|
||||
|
||||
`main` should keep direct merges restricted to the non-bypass merge actor
|
||||
used by the queue. Normal humans and agents should not merge directly.
|
||||
|
||||
`block_on_outdated_branch` should be enabled as a defense in depth, but it
|
||||
does not replace the queue. The queue still performs its own current-main
|
||||
check immediately before merge because branch protection alone cannot
|
||||
serialize two already-green PRs.
|
||||
|
||||
## Failure Handling
|
||||
|
||||
If `main` is not green, the queue pauses and does not merge anything.
|
||||
|
||||
If a queued PR is stale, the queue updates the PR branch and comments on the
|
||||
PR. It does not merge until CI runs on the updated head.
|
||||
|
||||
If the queue workflow fails, treat it as a CI/CD incident. Do not bypass by
|
||||
manually merging unless the human operator explicitly accepts the risk.
|
||||
@@ -129,12 +129,8 @@ YAML files ported from GitHub Actions. Manual triggers should use
|
||||
|
||||
## Quirk #4 — `merge_group` not supported
|
||||
|
||||
Gitea has no native merge queue concept. Drop `merge_group:` triggers from
|
||||
all workflow YAML files.
|
||||
|
||||
For `molecule-core`, use the external serialized queue documented in
|
||||
`runbooks/gitea-merge-queue.md`. Gitea's `pull_auto_merge` table is
|
||||
auto-merge-on-green, not a queue that retests each PR against latest `main`.
|
||||
Gitea has no merge queue concept. Drop `merge_group:` triggers from all
|
||||
workflow YAML files.
|
||||
|
||||
---
|
||||
|
||||
@@ -404,3 +400,4 @@ table if more than one is affected.>
|
||||
- [ ] **GITHUB_TOKEN auto-population**: internal #325 — is this on the
|
||||
Gitea 1.23 roadmap? If not, the workaround (named secret) is the permanent
|
||||
answer
|
||||
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
package bundle
|
||||
|
||||
// bundle_helpers_test.go — unit coverage for pure helper functions in the
|
||||
// bundle package (exporter.go, importer.go).
|
||||
//
|
||||
// Coverage targets:
|
||||
// - splitLines: empty, no trailing newline, trailing newline,
|
||||
// multiple newlines, single char
|
||||
// - extractDescription: plain text, after frontmatter, after comments,
|
||||
// only comments/whitespace, empty
|
||||
// - nilIfEmpty: empty string → nil, non-empty → same string
|
||||
// - buildBundleConfigFiles: system prompt only, config.yaml prompt,
|
||||
// skill files, combined, empty bundle
|
||||
// - findConfigDir: exact name match, fallback to first dir,
|
||||
// no match returns fallback, unreadable dir returns ""
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// ---------- splitLines ----------
|
||||
|
||||
func TestSplitLines_Basic(t *testing.T) {
|
||||
got := splitLines("a\nb\nc")
|
||||
want := []string{"a", "b", "c"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("len=%d; want %d", len(got), len(want))
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Errorf("got[%d]=%q; want %q", i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitLines_TrailingNewline(t *testing.T) {
|
||||
got := splitLines("a\nb\n")
|
||||
if len(got) != 2 {
|
||||
t.Errorf("trailing newline should not produce extra empty string; got %v (len=%d)", got, len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitLines_Empty(t *testing.T) {
|
||||
got := splitLines("")
|
||||
// An empty string should return a single-element slice containing ""
|
||||
if len(got) != 1 || got[0] != "" {
|
||||
t.Errorf("empty string should produce one empty-string element; got %v (len=%d)", got, len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitLines_SingleCharNoNewline(t *testing.T) {
|
||||
got := splitLines("x")
|
||||
if len(got) != 1 || got[0] != "x" {
|
||||
t.Errorf("single char; got %v (len=%d)", got, len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- extractDescription ----------
|
||||
|
||||
func TestExtractDescription_PlainText(t *testing.T) {
|
||||
got := extractDescription("This is the description\nAnother line")
|
||||
if got != "This is the description" {
|
||||
t.Errorf("got %q; want %q", got, "This is the description")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractDescription_AfterFrontmatter(t *testing.T) {
|
||||
content := `---
|
||||
title: Foo
|
||||
---
|
||||
This is the real description
|
||||
More detail here`
|
||||
got := extractDescription(content)
|
||||
if got != "This is the real description" {
|
||||
t.Errorf("got %q; want %q", got, "This is the real description")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractDescription_SkipsComments(t *testing.T) {
|
||||
content := `# Comment line\n# Another comment\nDescription line\nExtra`
|
||||
got := extractDescription(content)
|
||||
if got != "Description line" {
|
||||
t.Errorf("got %q; want %q", got, "Description line")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractDescription_OnlyComments(t *testing.T) {
|
||||
got := extractDescription("# Comment\n# Another")
|
||||
if got != "" {
|
||||
t.Errorf("only comments → want empty; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractDescription_Empty(t *testing.T) {
|
||||
got := extractDescription("")
|
||||
if got != "" {
|
||||
t.Errorf("empty → want empty; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractDescription_FrontmatterOnly(t *testing.T) {
|
||||
content := "---\nkey: value\n---"
|
||||
got := extractDescription(content)
|
||||
if got != "" {
|
||||
t.Errorf("frontmatter only → want empty; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- nilIfEmpty ----------
|
||||
|
||||
func TestNilIfEmpty_Empty(t *testing.T) {
|
||||
got := nilIfEmpty("")
|
||||
if got != nil {
|
||||
t.Errorf("nilIfEmpty(\"\") = %v; want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilIfEmpty_NonEmpty(t *testing.T) {
|
||||
got := nilIfEmpty("hello")
|
||||
if got != "hello" {
|
||||
t.Errorf("nilIfEmpty(\"hello\") = %v; want \"hello\"", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- buildBundleConfigFiles ----------
|
||||
|
||||
func TestBuildBundleConfigFiles_SystemPrompt(t *testing.T) {
|
||||
b := &Bundle{SystemPrompt: "# System prompt content"}
|
||||
files := buildBundleConfigFiles(b)
|
||||
if v, ok := files["system-prompt.md"]; !ok {
|
||||
t.Error("system-prompt.md missing")
|
||||
} else if string(v) != "# System prompt content" {
|
||||
t.Errorf("system-prompt.md = %q; want %q", v, "# System prompt content")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildBundleConfigFiles_ConfigYaml(t *testing.T) {
|
||||
b := &Bundle{Prompts: map[string]string{"config.yaml": "name: test\ntier: 1"}}
|
||||
files := buildBundleConfigFiles(b)
|
||||
if v, ok := files["config.yaml"]; !ok {
|
||||
t.Error("config.yaml missing from prompts")
|
||||
} else if string(v) != "name: test\ntier: 1" {
|
||||
t.Errorf("config.yaml = %q; want %q", v, "name: test\ntier: 1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildBundleConfigFiles_SkillFiles(t *testing.T) {
|
||||
b := &Bundle{
|
||||
Skills: []BundleSkill{
|
||||
{ID: "my-skill", Files: map[string]string{
|
||||
"SKILL.md": "# My Skill",
|
||||
"prompt.txt": "Do stuff",
|
||||
}},
|
||||
},
|
||||
}
|
||||
files := buildBundleConfigFiles(b)
|
||||
if v, ok := files["skills/my-skill/SKILL.md"]; !ok {
|
||||
t.Error("skills/my-skill/SKILL.md missing")
|
||||
} else if string(v) != "# My Skill" {
|
||||
t.Errorf("skills/my-skill/SKILL.md = %q; want %q", v, "# My Skill")
|
||||
}
|
||||
if v, ok := files["skills/my-skill/prompt.txt"]; !ok {
|
||||
t.Error("skills/my-skill/prompt.txt missing")
|
||||
} else if string(v) != "Do stuff" {
|
||||
t.Errorf("skills/my-skill/prompt.txt = %q; want %q", v, "Do stuff")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildBundleConfigFiles_Combined(t *testing.T) {
|
||||
b := &Bundle{
|
||||
SystemPrompt: "System",
|
||||
Prompts: map[string]string{"config.yaml": "cfg"},
|
||||
Skills: []BundleSkill{
|
||||
{ID: "s1", Files: map[string]string{"a.md": "A"}},
|
||||
},
|
||||
}
|
||||
files := buildBundleConfigFiles(b)
|
||||
if len(files) != 3 {
|
||||
t.Errorf("got %d files; want 3", len(files))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildBundleConfigFiles_Empty(t *testing.T) {
|
||||
b := &Bundle{}
|
||||
files := buildBundleConfigFiles(b)
|
||||
if len(files) != 0 {
|
||||
t.Errorf("empty bundle should produce no files; got %d", len(files))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- findConfigDir ----------
|
||||
|
||||
func TestFindConfigDir_ExactMatch(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
sub := filepath.Join(dir, "ws-abc")
|
||||
if err := os.MkdirAll(sub, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(sub, "config.yaml"), []byte("name: my-workspace\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got := findConfigDir(dir, "my-workspace")
|
||||
if got != sub {
|
||||
t.Errorf("got %q; want %q", got, sub)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindConfigDir_FallbackToFirst(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
sub1 := filepath.Join(dir, "ws-1")
|
||||
sub2 := filepath.Join(dir, "ws-2")
|
||||
os.MkdirAll(sub1, 0o755)
|
||||
os.MkdirAll(sub2, 0o755)
|
||||
os.WriteFile(filepath.Join(sub1, "config.yaml"), []byte("name: other\n"), 0o644)
|
||||
os.WriteFile(filepath.Join(sub2, "config.yaml"), []byte("name: another\n"), 0o644)
|
||||
|
||||
got := findConfigDir(dir, "nonexistent")
|
||||
if got != sub1 {
|
||||
t.Errorf("no match → fallback to first; got %q; want %q", got, sub1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindConfigDir_NoMatchNoFallback(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
// No subdirectories
|
||||
got := findConfigDir(dir, "anything")
|
||||
if got != "" {
|
||||
t.Errorf("no dirs → want empty; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindConfigDir_UnreadableDir(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
got := findConfigDir(dir, "anything")
|
||||
if got != "" {
|
||||
t.Errorf("unreadable top-level → want empty; got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -1,298 +1,253 @@
|
||||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
// delegation_executor_integration_test.go — REAL Postgres integration tests for
|
||||
// executeDelegation HTTP proxy edge cases that sqlmock cannot cover.
|
||||
// delegation_executor_integration_test.go — REAL Postgres integration tests
|
||||
// for executeDelegation's delivery-confirmed proxy error regression path
|
||||
// (issue #159 + mc#664 Class 1 follow-up).
|
||||
//
|
||||
// The sqlmock tests in delegation_test.go pin which SQL statements fire but
|
||||
// cannot detect bugs that depend on the row state AFTER the SQL runs. The
|
||||
// result_preview-lost bug shipped to staging in PR #2854 because sqlmock tests
|
||||
// were satisfied with "an UPDATE fired" — none verified the row's preview
|
||||
// field actually landed. These integration tests close that gap.
|
||||
// Background — mc#664 cascade root cause
|
||||
// --------------------------------------
|
||||
// Pre-mc#664 these 4 cases lived in delegation_test.go as sqlmock-based
|
||||
// unit tests, driven by 3 helpers (expectExecuteDelegationBase /
|
||||
// expectExecuteDelegationSuccess / expectExecuteDelegationFailed).
|
||||
// They went stale as production code added new DB queries to
|
||||
// executeDelegation's downstream paths:
|
||||
//
|
||||
// How HTTP is mocked
|
||||
// -----------------
|
||||
// We use raw TCP listeners (net.Listener) instead of httptest.Server to avoid
|
||||
// any HTTP-library-level goroutine complexity. The test opens a TCP port,
|
||||
// serves one HTTP response, then closes the connection. The a2aClient transport
|
||||
// is overridden with a DialContext that intercepts all dials and redirects to
|
||||
// the test server's port. No DNS, no TCP handshake overhead, no HTTP library
|
||||
// goroutines that could block on request-body reads.
|
||||
// 1. last_outbound_at UPDATE (a2a_proxy_helpers.go logA2ASuccess)
|
||||
// 2. lookupDeliveryMode SELECT (a2a_proxy.go poll-mode short-circuit)
|
||||
// 3. lookupRuntime SELECT (a2a_proxy.go mock-runtime short-circuit)
|
||||
// 4. a2a_receive INSERT into activity_logs (LogActivity goroutine)
|
||||
// 5. recordLedgerStatus writes (delegation.go + delegation_ledger.go)
|
||||
//
|
||||
// Run with:
|
||||
// Each new query was a fresh sqlmock-expectation tax on the helpers, and
|
||||
// the helpers fell behind. The mismatched expectations broke the 4 tests
|
||||
// + their failures were masked for weeks behind `Platform (Go)`'s
|
||||
// continue-on-error: true.
|
||||
//
|
||||
// Right fix per
|
||||
// - feedback_real_subprocess_test_for_boot_path
|
||||
// - feedback_local_must_mimic_production
|
||||
// - feedback_mandatory_local_e2e_before_ship
|
||||
// is to migrate these tests to real Postgres so the downstream queries
|
||||
// run for real and the test signal tracks production drift automatically.
|
||||
// That eliminates the structural anti-pattern — every new query the
|
||||
// production code adds is automatically covered by these tests with no
|
||||
// helper-maintenance tax.
|
||||
//
|
||||
// Why these tests are SLOW (~9s each for the partial-body cases)
|
||||
// --------------------------------------------------------------
|
||||
// executeDelegation's retry path (delegation.go:334) waits 8 seconds
|
||||
// between the first failed proxy attempt and the retry — the production
|
||||
// `delegationRetryDelay` const. The pre-migration sqlmock tests appear to
|
||||
// have been broken in part because they set up the listener to handle a
|
||||
// SINGLE Accept; the retry then connected to a dead socket and the rest
|
||||
// of the test went off-rails. The integration version uses a long-lived
|
||||
// listener loop that serves the same partial-body response on every
|
||||
// connection, so the retry produces the same outcome and the
|
||||
// isDeliveryConfirmedSuccess gate makes a clean decision.
|
||||
//
|
||||
// 9s × 3 partial-body tests + ~1s for the clean path = ~28s end-to-end.
|
||||
// Still well under CI's `-timeout 5m`. Local devs running `-run TestInt`
|
||||
// should pass `-timeout 60s` or higher.
|
||||
//
|
||||
// Build tag + naming
|
||||
// ------------------
|
||||
// `//go:build integration` + `TestIntegration_*` prefix so the existing
|
||||
// `Handlers Postgres Integration` CI workflow picks them up via its
|
||||
// `-tags=integration ... -run "^TestIntegration_"` runner. The same
|
||||
// shape as delegation_ledger_integration_test.go (the file these tests
|
||||
// were modelled after).
|
||||
//
|
||||
// Run locally:
|
||||
//
|
||||
// docker run --rm -d --name pg-integration \
|
||||
// -e POSTGRES_PASSWORD=test -e POSTGRES_DB=molecule \
|
||||
// -p 55432:5432 postgres:15-alpine
|
||||
// sleep 4
|
||||
// psql ... < workspace-server/migrations/049_delegations.up.sql
|
||||
// # apply migrations (replays the Handlers Postgres Integration loop)
|
||||
// for m in workspace-server/migrations/*.sql; do
|
||||
// [[ "$m" == *.down.sql ]] && continue
|
||||
// PGPASSWORD=test psql -h localhost -p 55432 -U postgres -d molecule \
|
||||
// -v ON_ERROR_STOP=1 -f "$m" >/dev/null 2>&1 || true
|
||||
// done
|
||||
// cd workspace-server
|
||||
// INTEGRATION_DB_URL="postgres://postgres:test@localhost:55432/molecule?sslmode=disable" \
|
||||
// go test -tags=integration ./internal/handlers/ -run Integration_ExecuteDelegation
|
||||
//
|
||||
// CI (.gitea/workflows/handlers-postgres-integration.yml) runs this on
|
||||
// every PR that touches workspace-server/internal/handlers/**.
|
||||
// go test -tags=integration -timeout 60s ./internal/handlers/ \
|
||||
// -run TestIntegration_ExecuteDelegation -v
|
||||
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Molecule-AI/molecule-monorepo/platform/internal/db"
|
||||
mdb "github.com/Molecule-AI/molecule-monorepo/platform/internal/db"
|
||||
)
|
||||
|
||||
// integrationDB is imported from delegation_ledger_integration_test.go.
|
||||
// Each test gets a fresh table state.
|
||||
// Real UUIDs — required because workspaces.id is UUID (not TEXT). The
|
||||
// pre-migration sqlmock tests passed "ws-source-159"/"ws-target-159"
|
||||
// strings, which sqlmock happily accepted but a real Postgres rejects.
|
||||
const (
|
||||
integExecSourceID = "11111111-aaaa-aaaa-aaaa-000000000159"
|
||||
integExecTargetID = "22222222-aaaa-aaaa-aaaa-000000000159"
|
||||
integExecDelegationID = "del-integ-159-test"
|
||||
)
|
||||
|
||||
const testDelegationID = "del-159-test-integration"
|
||||
const testSourceID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
const testTargetID = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
|
||||
// rawHTTPServer starts a TCP listener, serves one HTTP response, and closes.
|
||||
// It runs in a background goroutine so the test can proceed immediately after
|
||||
// returning the server URL. The server URL (e.g. "http://127.0.0.1:<port>/")
|
||||
// is suitable for caching in Redis and passing to executeDelegation.
|
||||
// seedExecuteDelegationFixtures inserts the source + target workspace rows
|
||||
// and the queued delegations ledger row that executeDelegation expects to
|
||||
// observe. Mirrors the pre-fix sqlmock helper's intent but in real DB
|
||||
// terms.
|
||||
//
|
||||
// The server reads HTTP headers using a deadline, then immediately sends the
|
||||
// response. This prevents the classic TCP deadlock: server blocked reading
|
||||
// body while client blocked waiting for response.
|
||||
func rawHTTPServer(t *testing.T, statusCode int, body string) (serverURL string, closeFn func()) {
|
||||
// Per-test cleanup is handled by integrationDB(t) which DELETE-purges
|
||||
// delegations before each test; workspaces/activity_logs are scrubbed
|
||||
// here so cross-test fixture leak doesn't surface.
|
||||
func seedExecuteDelegationFixtures(t *testing.T) {
|
||||
t.Helper()
|
||||
// Use ListenTCP with explicit IPv4 to avoid IPv6 mismatch on macOS
|
||||
// (Listen("tcp", "127.0.0.1:0") might bind ::1 on some systems).
|
||||
ln, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 0})
|
||||
if err != nil {
|
||||
t.Fatalf("rawHTTPServer listen: %v", err)
|
||||
conn := mdb.DB
|
||||
if _, err := conn.ExecContext(context.Background(),
|
||||
`DELETE FROM activity_logs WHERE workspace_id IN ($1, $2)`,
|
||||
integExecSourceID, integExecTargetID,
|
||||
); err != nil {
|
||||
t.Fatalf("cleanup activity_logs: %v", err)
|
||||
}
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
serverURL = "http://127.0.0.1:" + strconv.Itoa(port) + "/"
|
||||
|
||||
connCh := make(chan net.Conn, 1)
|
||||
go func() {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
if _, err := conn.ExecContext(context.Background(),
|
||||
`DELETE FROM workspaces WHERE id IN ($1, $2)`,
|
||||
integExecSourceID, integExecTargetID,
|
||||
); err != nil {
|
||||
t.Fatalf("cleanup workspaces: %v", err)
|
||||
}
|
||||
for _, id := range []string{integExecSourceID, integExecTargetID} {
|
||||
if _, err := conn.ExecContext(context.Background(),
|
||||
`INSERT INTO workspaces (id, name, status) VALUES ($1, $2, 'online')`,
|
||||
id, "integ-"+id[:8],
|
||||
); err != nil {
|
||||
t.Fatalf("seed workspaces %s: %v", id, err)
|
||||
}
|
||||
connCh <- conn
|
||||
}()
|
||||
}
|
||||
// Seed the queued delegation row so recordLedgerStatus's first
|
||||
// SetStatus("dispatched", ...) has somewhere to transition from.
|
||||
// Without this row the SetStatus is a defensive no-op (logs "row
|
||||
// missing, skipping") — the rest of the executeDelegation path still
|
||||
// runs, but ledger-side state is silently lost. We want it real.
|
||||
recordLedgerInsert(context.Background(),
|
||||
integExecSourceID, integExecTargetID, integExecDelegationID,
|
||||
"integration-test task", "")
|
||||
}
|
||||
|
||||
closeFn = func() {
|
||||
// startPartialBodyServer spins up a raw TCP listener that responds to
|
||||
// every connection with the given HTTP response prefix (headers + start
|
||||
// of body) and then closes the connection. Go's http.Client sees io.EOF
|
||||
// when reading the body. Returns the URL + a stop func.
|
||||
//
|
||||
// Unlike httptest.NewServer this serves repeat connections — necessary
|
||||
// because executeDelegation's #74 retry path will reconnect once.
|
||||
func startPartialBodyServer(t *testing.T, responseHead string) (url string, stop func()) {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
var done int32
|
||||
go func() {
|
||||
for atomic.LoadInt32(&done) == 0 {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func(c net.Conn) {
|
||||
defer c.Close()
|
||||
buf := make([]byte, 2048)
|
||||
_, _ = c.Read(buf)
|
||||
_, _ = c.Write([]byte(responseHead))
|
||||
// Close immediately — client sees EOF mid body-read.
|
||||
}(conn)
|
||||
}
|
||||
}()
|
||||
return "http://" + ln.Addr().String(), func() {
|
||||
atomic.StoreInt32(&done, 1)
|
||||
ln.Close()
|
||||
}
|
||||
|
||||
// Handle in background so we don't block test execution.
|
||||
// Strategy: read available bytes with a deadline (enough for headers).
|
||||
// After deadline fires, send the response immediately.
|
||||
// The kernel discards any unread buffered body bytes when the
|
||||
// connection closes — harmless.
|
||||
go func() {
|
||||
conn := <-connCh
|
||||
if conn == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Read what we can with a 2s deadline. Headers always arrive first.
|
||||
conn.SetReadDeadline(time.Now().Add(2 * time.Second))
|
||||
headerBuf := make([]byte, 4096)
|
||||
for {
|
||||
n, err := conn.Read(headerBuf)
|
||||
if n > 0 {
|
||||
_ = headerBuf[:n]
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Send response and IMMEDIATELY close the connection.
|
||||
// If we keep it open, the client's request-body writer goroutine
|
||||
// might block on the socket (waiting for the server to drain the
|
||||
// body). Closing immediately unblocks it. The client already
|
||||
// received the response, so the write error is harmless.
|
||||
resp := buildHTTPResponse(statusCode, body)
|
||||
conn.Write(resp) //nolint:errcheck
|
||||
conn.Close()
|
||||
}()
|
||||
|
||||
return serverURL, closeFn
|
||||
}
|
||||
|
||||
// buildHTTPResponse constructs a minimal HTTP/1.1 response.
|
||||
func buildHTTPResponse(statusCode int, body string) []byte {
|
||||
statusText := http.StatusText(statusCode)
|
||||
if statusText == "" {
|
||||
statusText = "Unknown"
|
||||
}
|
||||
header := "HTTP/1.1 " + strconv.Itoa(statusCode) + " " + statusText + "\r\n" +
|
||||
"Content-Type: application/json\r\n" +
|
||||
"Content-Length: " + strconv.Itoa(len(body)) + "\r\n" +
|
||||
"Connection: close\r\n" +
|
||||
"\r\n"
|
||||
return []byte(header + body)
|
||||
}
|
||||
|
||||
// setupIntegrationFixtures inserts the rows executeDelegation requires:
|
||||
// - workspaces: source and target (siblings, parent_id=NULL so CanCommunicate=true)
|
||||
// - activity_logs: the 'delegate' row that updateDelegationStatus UPDATE will find
|
||||
// - delegations: the ledger row that recordLedgerStatus will UPDATE
|
||||
//
|
||||
// Returns a cleanup function the test should defer.
|
||||
func setupIntegrationFixtures(t *testing.T, conn *sql.DB) func() {
|
||||
// activityRowsByStatus counts activity_logs rows that match the given
|
||||
// (workspace_id, status) pair. Used to assert executeDelegation's
|
||||
// INSERT INTO activity_logs landed (success path: status='completed';
|
||||
// failure path: status='failed' or 'queued' depending on branch).
|
||||
func activityRowsByStatus(t *testing.T, workspaceID, status string) int {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
for _, ws := range []struct {
|
||||
id string
|
||||
name string
|
||||
parentID *string
|
||||
}{
|
||||
{testSourceID, "test-source", nil},
|
||||
{testTargetID, "test-target", nil},
|
||||
} {
|
||||
if _, err := conn.ExecContext(ctx,
|
||||
`INSERT INTO workspaces (id, name, parent_id) VALUES ($1::uuid, $2, $3) ON CONFLICT (id) DO NOTHING`,
|
||||
ws.id, ws.name, ws.parentID,
|
||||
); err != nil {
|
||||
cancel()
|
||||
t.Fatalf("seed workspace %s: %v", ws.id, err)
|
||||
}
|
||||
}
|
||||
|
||||
reqBody, _ := json.Marshal(map[string]any{
|
||||
"delegation_id": testDelegationID,
|
||||
"task": "do work",
|
||||
})
|
||||
if _, err := conn.ExecContext(ctx, `
|
||||
INSERT INTO activity_logs
|
||||
(workspace_id, activity_type, method, source_id, target_id, request_body, status)
|
||||
VALUES ($1, 'delegate', 'delegate', $1, $2, $3::jsonb, 'pending')
|
||||
ON CONFLICT DO NOTHING
|
||||
`, testSourceID, testTargetID, string(reqBody)); err != nil {
|
||||
cancel()
|
||||
t.Fatalf("seed activity_logs: %v", err)
|
||||
}
|
||||
|
||||
if _, err := conn.ExecContext(ctx, `
|
||||
INSERT INTO delegations
|
||||
(delegation_id, caller_id, callee_id, task_preview, status)
|
||||
VALUES ($1, $2::uuid, $3::uuid, 'do work', 'queued')
|
||||
ON CONFLICT (delegation_id) DO NOTHING
|
||||
`, testDelegationID, testSourceID, testTargetID); err != nil {
|
||||
cancel()
|
||||
t.Fatalf("seed delegations: %v", err)
|
||||
}
|
||||
cancel()
|
||||
|
||||
return func() {
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel2()
|
||||
conn.ExecContext(ctx2,
|
||||
`DELETE FROM activity_logs WHERE workspace_id = $1 AND request_body->>'delegation_id' = $2`,
|
||||
testSourceID, testDelegationID)
|
||||
conn.ExecContext(ctx2,
|
||||
`DELETE FROM delegations WHERE delegation_id = $1`, testDelegationID)
|
||||
conn.ExecContext(ctx2,
|
||||
`DELETE FROM workspaces WHERE id IN ($1, $2)`, testSourceID, testTargetID)
|
||||
var n int
|
||||
if err := mdb.DB.QueryRowContext(context.Background(),
|
||||
`SELECT count(*) FROM activity_logs WHERE workspace_id = $1 AND status = $2`,
|
||||
workspaceID, status,
|
||||
).Scan(&n); err != nil {
|
||||
t.Fatalf("activity count(%s, %s): %v", workspaceID, status, err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// readDelegationRow returns (status, result_preview, error_detail) for the test
|
||||
// delegation, or fails the test if the row is not found.
|
||||
func readDelegationRow(t *testing.T, conn *sql.DB) (status, preview, errorDetail string) {
|
||||
// delegationLedgerStatus returns the current delegations.status for the
|
||||
// seeded delegation_id, or "" if the row is missing. Real-Postgres
|
||||
// version of "did the ledger transition we expected actually land".
|
||||
func delegationLedgerStatus(t *testing.T, delegationID string) string {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
var prev, errDet sql.NullString
|
||||
err := conn.QueryRowContext(ctx,
|
||||
`SELECT status, result_preview, error_detail FROM delegations WHERE delegation_id = $1`,
|
||||
testDelegationID,
|
||||
).Scan(&status, &prev, &errDet)
|
||||
var s string
|
||||
err := mdb.DB.QueryRowContext(context.Background(),
|
||||
`SELECT status FROM delegations WHERE delegation_id = $1`, delegationID,
|
||||
).Scan(&s)
|
||||
if err != nil {
|
||||
t.Fatalf("readDelegationRow: %v", err)
|
||||
}
|
||||
return status, prev.String, errDet.String
|
||||
}
|
||||
|
||||
// stack returns the current goroutine stack trace. Used by runWithTimeout to
|
||||
// pinpoint the blocking call site when a test times out.
|
||||
func stack() string {
|
||||
buf := make([]byte, 4096)
|
||||
n := runtime.Stack(buf, false)
|
||||
return string(buf[:n])
|
||||
}
|
||||
|
||||
// runWithTimeout calls fn in a goroutine and fails t if it doesn't return within
|
||||
// timeout. ctx is passed to fn so it can propagate cancellation to
|
||||
// executeDelegation's DB and network operations — without this, the goroutine
|
||||
// leaks indefinitely when the test times out (context.Background() never cancels).
|
||||
func runWithTimeout(t *testing.T, timeout time.Duration, fn func(context.Context)) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
done := make(chan struct{})
|
||||
var panicErr interface{}
|
||||
go func() {
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
panicErr = p
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
fn(ctx)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
if panicErr != nil {
|
||||
t.Fatalf("executeDelegation panicked: %v\n%s", panicErr, stack())
|
||||
}
|
||||
case <-ctx.Done():
|
||||
cancel()
|
||||
t.Fatalf("executeDelegation timed out after %s\n%s", timeout, stack())
|
||||
t.Fatalf("ledger status(%s): %v", delegationID, err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// TestIntegration_ExecuteDelegation_DeliveryConfirmedProxyError_TreatsAsSuccess
|
||||
// is the integration regression gate for issue #159.
|
||||
// is the primary regression test for issue #159 in real-Postgres form.
|
||||
// Scenario: target sends a 200 response with declared Content-Length but
|
||||
// closes the connection mid-body; client gets io.EOF on body read.
|
||||
// proxyA2ARequest captures status=200 + partial body + transport error;
|
||||
// executeDelegation's isDeliveryConfirmedSuccess branch must route to
|
||||
// handleSuccess so the row lands as 'completed' (not 'failed').
|
||||
//
|
||||
// Scenario: proxyA2ARequest returns a 200 status code with a non-empty body.
|
||||
// isDeliveryConfirmedSuccess guard (status>=200 && <300 && len(body)>0 && err!=nil)
|
||||
// routes to handleSuccess. The integration test verifies the DB row lands at
|
||||
// 'completed' with the response body as result_preview.
|
||||
// Real-Postgres advantage over the sqlmock version: this test will fail
|
||||
// if a future refactor adds a new DB write to the success path without
|
||||
// updating any helper — sqlmock would have required reflexive expectation
|
||||
// updates; real Postgres just runs.
|
||||
//
|
||||
// Timing: executeDelegation's first attempt returns (200, <partial>, EOF
|
||||
// → BadGateway-class err). isTransientProxyError(BadGateway)=true so the
|
||||
// caller sleeps `delegationRetryDelay` (8s) and retries. Our listener
|
||||
// loop serves the same partial response on attempt 2, producing the
|
||||
// same (200, <partial>, BadGateway) triple. isDeliveryConfirmedSuccess
|
||||
// then fires (status=200 ∈ [200,300) + body > 0 + err != nil) → success.
|
||||
func TestIntegration_ExecuteDelegation_DeliveryConfirmedProxyError_TreatsAsSuccess(t *testing.T) {
|
||||
allowLoopbackForTest(t)
|
||||
conn := integrationDB(t)
|
||||
cleanup := setupIntegrationFixtures(t, conn)
|
||||
defer cleanup()
|
||||
integrationDB(t)
|
||||
t.Setenv("DELEGATION_LEDGER_WRITE", "1")
|
||||
|
||||
agentURL, closeServer := rawHTTPServer(t, 200, `{"result":{"parts":[{"text":"work completed successfully"}]}}`)
|
||||
defer closeServer()
|
||||
seedExecuteDelegationFixtures(t)
|
||||
|
||||
mr := setupTestRedis(t)
|
||||
defer mr.Close()
|
||||
db.CacheURL(context.Background(), testTargetID, agentURL)
|
||||
|
||||
prevClient := a2aClient
|
||||
defer func() { a2aClient = prevClient }()
|
||||
a2aClient = newA2AClientForHost(extractHostPort(agentURL))
|
||||
|
||||
allowLoopbackForTest(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
wh := NewWorkspaceHandler(broadcaster, nil, "http://localhost:8080", t.TempDir())
|
||||
dh := NewDelegationHandler(wh, broadcaster)
|
||||
|
||||
// 200 OK with declared Content-Length=100 but only 74 bytes of body.
|
||||
// Connection closes after the partial body → client io.EOF.
|
||||
resp := "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 100\r\n\r\n"
|
||||
resp += `{"result":{"parts":[{"text":"work completed successfully"}]}}` // 74 bytes
|
||||
agentURL, stop := startPartialBodyServer(t, resp)
|
||||
defer stop()
|
||||
|
||||
mr.Set(fmt.Sprintf("ws:%s:url", integExecTargetID), agentURL)
|
||||
|
||||
a2aBody, _ := json.Marshal(map[string]interface{}{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "1",
|
||||
"method": "message/send",
|
||||
"jsonrpc": "2.0", "id": "1", "method": "message/send",
|
||||
"params": map[string]interface{}{
|
||||
"message": map[string]interface{}{
|
||||
"role": "user",
|
||||
@@ -300,50 +255,46 @@ func TestIntegration_ExecuteDelegation_DeliveryConfirmedProxyError_TreatsAsSucce
|
||||
},
|
||||
},
|
||||
})
|
||||
dh.executeDelegation(integExecSourceID, integExecTargetID, integExecDelegationID, a2aBody)
|
||||
|
||||
start := time.Now()
|
||||
runWithTimeout(t, 30*time.Second, func(ctx context.Context) {
|
||||
dh.executeDelegation(ctx, testSourceID, testTargetID, testDelegationID, a2aBody)
|
||||
})
|
||||
t.Logf("executeDelegation took %v", time.Since(start))
|
||||
// executeDelegation is synchronous here; the 8s retry sleep is INSIDE
|
||||
// the call. We still need a small buffer for the async logA2ASuccess /
|
||||
// last_outbound_at goroutines that fan out after the success branch.
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
status, preview, errDet := readDelegationRow(t, conn)
|
||||
if status != "completed" {
|
||||
t.Errorf("status: want completed, got %q", status)
|
||||
// Assert the executeDelegation success path wrote the activity_logs
|
||||
// completion row + transitioned the ledger to completed.
|
||||
if got := activityRowsByStatus(t, integExecSourceID, "completed"); got != 1 {
|
||||
t.Errorf("expected 1 'completed' activity_logs row, got %d", got)
|
||||
}
|
||||
if preview == "" {
|
||||
t.Errorf("result_preview should be non-empty, got %q", preview)
|
||||
}
|
||||
if errDet != "" {
|
||||
t.Errorf("error_detail should be empty on success: got %q", errDet)
|
||||
if s := delegationLedgerStatus(t, integExecDelegationID); s != "completed" {
|
||||
t.Errorf("delegation ledger: want status=completed, got %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntegration_ExecuteDelegation_ProxyErrorNon2xx_RemainsFailed verifies that
|
||||
// a 500 response routes to failure, not success. isDeliveryConfirmedSuccess
|
||||
// requires status>=200 && <300, so 500 always fails the guard.
|
||||
// TestIntegration_ExecuteDelegation_ProxyErrorNon2xx_RemainsFailed —
|
||||
// 500 with partial body + connection drop. The retry produces the same
|
||||
// 500 partial. isDeliveryConfirmedSuccess fails on status>=300 → falls
|
||||
// through to the failure branch. Pins that the new condition didn't
|
||||
// accidentally widen the success branch.
|
||||
func TestIntegration_ExecuteDelegation_ProxyErrorNon2xx_RemainsFailed(t *testing.T) {
|
||||
allowLoopbackForTest(t)
|
||||
conn := integrationDB(t)
|
||||
cleanup := setupIntegrationFixtures(t, conn)
|
||||
defer cleanup()
|
||||
integrationDB(t)
|
||||
t.Setenv("DELEGATION_LEDGER_WRITE", "1")
|
||||
|
||||
agentURL, closeServer := rawHTTPServer(t, 500, `{"error":"agent crashed"}`)
|
||||
defer closeServer()
|
||||
seedExecuteDelegationFixtures(t)
|
||||
|
||||
mr := setupTestRedis(t)
|
||||
defer mr.Close()
|
||||
db.CacheURL(context.Background(), testTargetID, agentURL)
|
||||
|
||||
prevClient := a2aClient
|
||||
defer func() { a2aClient = prevClient }()
|
||||
a2aClient = newA2AClientForHost(extractHostPort(agentURL))
|
||||
|
||||
allowLoopbackForTest(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
wh := NewWorkspaceHandler(broadcaster, nil, "http://localhost:8080", t.TempDir())
|
||||
dh := NewDelegationHandler(wh, broadcaster)
|
||||
|
||||
resp := "HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: 100\r\n\r\n"
|
||||
resp += `{"error":"agent crashed"}` // ~24 bytes, less than declared 100
|
||||
agentURL, stop := startPartialBodyServer(t, resp)
|
||||
defer stop()
|
||||
|
||||
mr.Set(fmt.Sprintf("ws:%s:url", integExecTargetID), agentURL)
|
||||
|
||||
a2aBody, _ := json.Marshal(map[string]interface{}{
|
||||
"jsonrpc": "2.0", "id": "1", "method": "message/send",
|
||||
"params": map[string]interface{}{
|
||||
@@ -353,46 +304,41 @@ func TestIntegration_ExecuteDelegation_ProxyErrorNon2xx_RemainsFailed(t *testing
|
||||
},
|
||||
},
|
||||
})
|
||||
start := time.Now()
|
||||
runWithTimeout(t, 30*time.Second, func(ctx context.Context) {
|
||||
dh.executeDelegation(ctx, testSourceID, testTargetID, testDelegationID, a2aBody)
|
||||
})
|
||||
t.Logf("executeDelegation took %v", time.Since(start))
|
||||
dh.executeDelegation(integExecSourceID, integExecTargetID, integExecDelegationID, a2aBody)
|
||||
|
||||
status, _, errDet := readDelegationRow(t, conn)
|
||||
if status != "failed" {
|
||||
t.Errorf("status: want failed, got %q", status)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
if got := activityRowsByStatus(t, integExecSourceID, "failed"); got != 1 {
|
||||
t.Errorf("expected 1 'failed' activity_logs row, got %d", got)
|
||||
}
|
||||
if errDet == "" {
|
||||
t.Error("error_detail should be non-empty on failure")
|
||||
if s := delegationLedgerStatus(t, integExecDelegationID); s != "failed" {
|
||||
t.Errorf("delegation ledger: want status=failed, got %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntegration_ExecuteDelegation_ProxyErrorEmptyBody_RemainsFailed verifies that
|
||||
// a 200 response with an empty body routes to failure. isDeliveryConfirmedSuccess
|
||||
// requires len(body) > 0, so an empty body fails the guard.
|
||||
// TestIntegration_ExecuteDelegation_ProxyErrorEmptyBody_RemainsFailed —
|
||||
// 502 Bad Gateway with empty body, normal close. proxyA2ARequest returns
|
||||
// (502, "", error). isDeliveryConfirmedSuccess requires len(respBody) > 0
|
||||
// → false → falls through to the failure branch. isTransientProxyError
|
||||
// (BadGateway) = true so we get a retry that also fails, then 'failed'.
|
||||
func TestIntegration_ExecuteDelegation_ProxyErrorEmptyBody_RemainsFailed(t *testing.T) {
|
||||
allowLoopbackForTest(t)
|
||||
conn := integrationDB(t)
|
||||
cleanup := setupIntegrationFixtures(t, conn)
|
||||
defer cleanup()
|
||||
integrationDB(t)
|
||||
t.Setenv("DELEGATION_LEDGER_WRITE", "1")
|
||||
|
||||
agentURL, closeServer := rawHTTPServer(t, 200, "")
|
||||
defer closeServer()
|
||||
seedExecuteDelegationFixtures(t)
|
||||
|
||||
mr := setupTestRedis(t)
|
||||
defer mr.Close()
|
||||
db.CacheURL(context.Background(), testTargetID, agentURL)
|
||||
|
||||
prevClient := a2aClient
|
||||
defer func() { a2aClient = prevClient }()
|
||||
a2aClient = newA2AClientForHost(extractHostPort(agentURL))
|
||||
|
||||
allowLoopbackForTest(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
wh := NewWorkspaceHandler(broadcaster, nil, "http://localhost:8080", t.TempDir())
|
||||
dh := NewDelegationHandler(wh, broadcaster)
|
||||
|
||||
agentServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
}))
|
||||
defer agentServer.Close()
|
||||
|
||||
mr.Set(fmt.Sprintf("ws:%s:url", integExecTargetID), agentServer.URL)
|
||||
|
||||
a2aBody, _ := json.Marshal(map[string]interface{}{
|
||||
"jsonrpc": "2.0", "id": "1", "method": "message/send",
|
||||
"params": map[string]interface{}{
|
||||
@@ -402,45 +348,43 @@ func TestIntegration_ExecuteDelegation_ProxyErrorEmptyBody_RemainsFailed(t *test
|
||||
},
|
||||
},
|
||||
})
|
||||
start := time.Now()
|
||||
runWithTimeout(t, 30*time.Second, func(ctx context.Context) {
|
||||
dh.executeDelegation(ctx, testSourceID, testTargetID, testDelegationID, a2aBody)
|
||||
})
|
||||
t.Logf("executeDelegation took %v", time.Since(start))
|
||||
dh.executeDelegation(integExecSourceID, integExecTargetID, integExecDelegationID, a2aBody)
|
||||
|
||||
status, _, errDet := readDelegationRow(t, conn)
|
||||
if status != "failed" {
|
||||
t.Errorf("status: want failed, got %q", status)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
if got := activityRowsByStatus(t, integExecSourceID, "failed"); got != 1 {
|
||||
t.Errorf("expected 1 'failed' activity_logs row, got %d", got)
|
||||
}
|
||||
if errDet == "" {
|
||||
t.Error("error_detail should be non-empty on failure")
|
||||
if s := delegationLedgerStatus(t, integExecDelegationID); s != "failed" {
|
||||
t.Errorf("delegation ledger: want status=failed, got %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntegration_ExecuteDelegation_CleanProxyResponse_Unchanged is the baseline:
|
||||
// a clean 200 response with a valid body and no error routes to success.
|
||||
// TestIntegration_ExecuteDelegation_CleanProxyResponse_Unchanged —
|
||||
// baseline: clean 200 with full body, no error. proxyErr == nil so
|
||||
// isDeliveryConfirmedSuccess never fires and no retry runs (fast path).
|
||||
// Pins that the new error-recovery branch didn't regress the most
|
||||
// common code path.
|
||||
func TestIntegration_ExecuteDelegation_CleanProxyResponse_Unchanged(t *testing.T) {
|
||||
allowLoopbackForTest(t)
|
||||
conn := integrationDB(t)
|
||||
cleanup := setupIntegrationFixtures(t, conn)
|
||||
defer cleanup()
|
||||
integrationDB(t)
|
||||
t.Setenv("DELEGATION_LEDGER_WRITE", "1")
|
||||
|
||||
agentURL, closeServer := rawHTTPServer(t, 200, `{"result":{"parts":[{"text":"all good"}]}}`)
|
||||
defer closeServer()
|
||||
seedExecuteDelegationFixtures(t)
|
||||
|
||||
mr := setupTestRedis(t)
|
||||
defer mr.Close()
|
||||
db.CacheURL(context.Background(), testTargetID, agentURL)
|
||||
|
||||
prevClient := a2aClient
|
||||
defer func() { a2aClient = prevClient }()
|
||||
a2aClient = newA2AClientForHost(extractHostPort(agentURL))
|
||||
|
||||
allowLoopbackForTest(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
wh := NewWorkspaceHandler(broadcaster, nil, "http://localhost:8080", t.TempDir())
|
||||
dh := NewDelegationHandler(wh, broadcaster)
|
||||
|
||||
agentServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"result":{"parts":[{"text":"all good"}]}}`))
|
||||
}))
|
||||
defer agentServer.Close()
|
||||
|
||||
mr.Set(fmt.Sprintf("ws:%s:url", integExecTargetID), agentServer.URL)
|
||||
|
||||
a2aBody, _ := json.Marshal(map[string]interface{}{
|
||||
"jsonrpc": "2.0", "id": "1", "method": "message/send",
|
||||
"params": map[string]interface{}{
|
||||
@@ -450,86 +394,14 @@ func TestIntegration_ExecuteDelegation_CleanProxyResponse_Unchanged(t *testing.T
|
||||
},
|
||||
},
|
||||
})
|
||||
start := time.Now()
|
||||
runWithTimeout(t, 30*time.Second, func(ctx context.Context) {
|
||||
dh.executeDelegation(ctx, testSourceID, testTargetID, testDelegationID, a2aBody)
|
||||
})
|
||||
t.Logf("executeDelegation took %v", time.Since(start))
|
||||
dh.executeDelegation(integExecSourceID, integExecTargetID, integExecDelegationID, a2aBody)
|
||||
|
||||
status, preview, errDet := readDelegationRow(t, conn)
|
||||
if status != "completed" {
|
||||
t.Errorf("status: want completed, got %q", status)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
if got := activityRowsByStatus(t, integExecSourceID, "completed"); got != 1 {
|
||||
t.Errorf("expected 1 'completed' activity_logs row, got %d", got)
|
||||
}
|
||||
if preview == "" {
|
||||
t.Errorf("result_preview should be non-empty, got %q", preview)
|
||||
}
|
||||
if errDet != "" {
|
||||
t.Errorf("error_detail should be empty on success: got %q", errDet)
|
||||
}
|
||||
}
|
||||
|
||||
// Test that a delegation where Redis cannot be reached still routes to failure
|
||||
// (not panic). proxyA2ARequest falls back to DB URL lookup when Redis is down.
|
||||
func TestIntegration_ExecuteDelegation_RedisDown_FallsBackToDB(t *testing.T) {
|
||||
allowLoopbackForTest(t)
|
||||
conn := integrationDB(t)
|
||||
cleanup := setupIntegrationFixtures(t, conn)
|
||||
defer cleanup()
|
||||
t.Setenv("DELEGATION_LEDGER_WRITE", "1")
|
||||
|
||||
// Set up miniredis so db.RDB is non-nil, but do NOT cache any URL.
|
||||
// resolveAgentURL skips Redis and falls back to DB, which also has no URL.
|
||||
mr := setupTestRedis(t)
|
||||
defer mr.Close()
|
||||
|
||||
broadcaster := newTestBroadcaster()
|
||||
wh := NewWorkspaceHandler(broadcaster, nil, "http://localhost:8080", t.TempDir())
|
||||
dh := NewDelegationHandler(wh, broadcaster)
|
||||
|
||||
a2aBody, _ := json.Marshal(map[string]interface{}{
|
||||
"jsonrpc": "2.0", "id": "1", "method": "message/send",
|
||||
"params": map[string]interface{}{
|
||||
"message": map[string]interface{}{
|
||||
"role": "user",
|
||||
"parts": []map[string]string{{"type": "text", "text": "do work"}},
|
||||
},
|
||||
},
|
||||
})
|
||||
start := time.Now()
|
||||
runWithTimeout(t, 30*time.Second, func(ctx context.Context) {
|
||||
dh.executeDelegation(ctx, testSourceID, testTargetID, testDelegationID, a2aBody)
|
||||
})
|
||||
t.Logf("executeDelegation took %v", time.Since(start))
|
||||
|
||||
status, _, errDet := readDelegationRow(t, conn)
|
||||
if status != "failed" {
|
||||
t.Errorf("status: want failed (no target URL), got %q", status)
|
||||
}
|
||||
if errDet == "" {
|
||||
t.Error("error_detail should be set on failure due to unreachable target")
|
||||
}
|
||||
}
|
||||
|
||||
// extractHostPort parses "http://127.0.0.1:PORT/" and returns "127.0.0.1:PORT".
|
||||
func extractHostPort(rawURL string) string {
|
||||
// Simple parse: strip "http://" prefix and trailing slash.
|
||||
// The URL format is always "http://127.0.0.1:PORT/" in our usage.
|
||||
if len(rawURL) > 7 {
|
||||
return rawURL[7 : len(rawURL)-1]
|
||||
}
|
||||
return rawURL
|
||||
}
|
||||
|
||||
// newA2AClientForHost creates an http.Client that redirects all connections
|
||||
// to the given host:port. This lets us mock the agent endpoint without
|
||||
// running a real HTTP server.
|
||||
func newA2AClientForHost(targetHost string) *http.Client {
|
||||
return &http.Client{
|
||||
Transport: &http.Transport{
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return net.Dial("tcp", targetHost)
|
||||
},
|
||||
ResponseHeaderTimeout: 180 * time.Second,
|
||||
},
|
||||
if s := delegationLedgerStatus(t, integExecDelegationID); s != "completed" {
|
||||
t.Errorf("delegation ledger: want status=completed, got %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,653 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// instructions_test.go — unit coverage for InstructionsHandler.
|
||||
//
|
||||
// Coverage targets:
|
||||
// - List: workspace_id scope (returns global + workspace); global-only scope;
|
||||
// query error propagation.
|
||||
// - Create: happy path; missing required fields; invalid scope; workspace scope
|
||||
// without scope_target; content too long; title too long; insert error.
|
||||
// - Update: happy path; partial update; content too long; title too long;
|
||||
// not found; update error.
|
||||
// - Delete: happy path; not found; delete error.
|
||||
// - Resolve: no instructions; global only; global + workspace; query error.
|
||||
|
||||
// setupInstructionsTestDB sets up a sqlmock DB attached to the global db.DB
|
||||
// and returns both the mock and a gin engine that uses it.
|
||||
// The caller MUST use the returned gin engine for BOTH route registration
|
||||
// AND for r.ServeHTTP — using a different engine for either step breaks routing.
|
||||
func setupInstructionsTestDB(t *testing.T) (sqlmock.Sqlmock, *gin.Engine) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mockDB, mock, err := sqlmock.New()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create sqlmock: %v", err)
|
||||
}
|
||||
db.DB = mockDB
|
||||
t.Cleanup(func() { mockDB.Close() })
|
||||
|
||||
// Disable SSRF checks for the duration of this test only.
|
||||
restore := setSSRFCheckForTest(false)
|
||||
t.Cleanup(restore)
|
||||
|
||||
// Wire mock into a gin engine so route registration and serving use the
|
||||
// same engine (avoids the "routes on r2, ServeHTTP on r" mismatch bug).
|
||||
r := gin.New()
|
||||
return mock, r
|
||||
}
|
||||
|
||||
// setupInstructionsTest is kept for backward compatibility with tests that
|
||||
// don't need a gin engine (pure validation helpers). All DB-dependent tests
|
||||
// should use setupInstructionsTestDB instead.
|
||||
func setupInstructionsTest(t *testing.T) (sqlmock.Sqlmock, *gin.Engine) {
|
||||
return setupInstructionsTestDB(t)
|
||||
}
|
||||
|
||||
// ---------- List ----------
|
||||
|
||||
func TestInstructionsList_WorkspaceScope(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.GET("/instructions", h.List)
|
||||
|
||||
mock.ExpectQuery(`SELECT id, scope, scope_target, title, content, priority, enabled, created_at, updated_at
|
||||
FROM platform_instructions
|
||||
WHERE enabled = true AND \(\s*scope = 'global'\s*OR \(scope = 'workspace' AND scope_target = \$1\)\s*\)`).
|
||||
WithArgs("ws-uuid-123").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "scope", "scope_target", "title", "content", "priority", "enabled", "created_at", "updated_at"}).
|
||||
AddRow("inst-1", "global", nil, "Global Rule", "Be nice", 10, true, "2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z").
|
||||
AddRow("inst-2", "workspace", stringPtr("ws-uuid-123"), "WS Rule", "Use dark mode", 5, true, "2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"))
|
||||
|
||||
req, _ := http.NewRequest("GET", "/instructions?workspace_id=ws-uuid-123", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var resp []Instruction
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to unmarshal response: %v", err)
|
||||
}
|
||||
if len(resp) != 2 {
|
||||
t.Errorf("expected 2 instructions, got %d", len(resp))
|
||||
}
|
||||
if resp[0].Scope != "global" {
|
||||
t.Errorf("expected global scope, got %s", resp[0].Scope)
|
||||
}
|
||||
if resp[1].Scope != "workspace" {
|
||||
t.Errorf("expected workspace scope, got %s", resp[1].Scope)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsList_GlobalOnlyScope(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.GET("/instructions", h.List)
|
||||
|
||||
mock.ExpectQuery(`SELECT id, scope, scope_target, title, content, priority, enabled, created_at, updated_at
|
||||
FROM platform_instructions WHERE 1=1`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "scope", "scope_target", "title", "content", "priority", "enabled", "created_at", "updated_at"}).
|
||||
AddRow("inst-1", "global", nil, "Global Rule", "Be nice", 10, true, "2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"))
|
||||
|
||||
req, _ := http.NewRequest("GET", "/instructions?scope=global", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsList_QueryError(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.GET("/instructions", h.List)
|
||||
|
||||
mock.ExpectQuery(`SELECT id, scope, scope_target, title, content, priority, enabled, created_at, updated_at
|
||||
FROM platform_instructions WHERE 1=1`).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
req, _ := http.NewRequest("GET", "/instructions", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Create ----------
|
||||
|
||||
func TestInstructionsCreate_HappyPath(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.POST("/instructions", h.Create)
|
||||
|
||||
mock.ExpectQuery(`INSERT INTO platform_instructions`).
|
||||
WithArgs("global", nil, "Test Title", "Test Content", 5).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow("new-inst-123"))
|
||||
|
||||
body := map[string]interface{}{
|
||||
"scope": "global",
|
||||
"title": "Test Title",
|
||||
"content": "Test Content",
|
||||
"priority": 5,
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("POST", "/instructions", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Errorf("expected 201, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]string
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to unmarshal response: %v", err)
|
||||
}
|
||||
if resp["id"] != "new-inst-123" {
|
||||
t.Errorf("expected id new-inst-123, got %s", resp["id"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsCreate_MissingRequired(t *testing.T) {
|
||||
_, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.POST("/instructions", h.Create)
|
||||
|
||||
// Missing scope
|
||||
body := map[string]interface{}{
|
||||
"title": "Test",
|
||||
"content": "Test",
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("POST", "/instructions", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsCreate_InvalidScope(t *testing.T) {
|
||||
_, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.POST("/instructions", h.Create)
|
||||
|
||||
body := map[string]interface{}{
|
||||
"scope": "invalid",
|
||||
"title": "Test",
|
||||
"content": "Test",
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("POST", "/instructions", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsCreate_WorkspaceScopeWithoutTarget(t *testing.T) {
|
||||
_, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.POST("/instructions", h.Create)
|
||||
|
||||
body := map[string]interface{}{
|
||||
"scope": "workspace",
|
||||
"title": "Test",
|
||||
"content": "Test",
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("POST", "/instructions", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsCreate_ContentTooLong(t *testing.T) {
|
||||
_, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.POST("/instructions", h.Create)
|
||||
|
||||
// Content > 8192 chars
|
||||
longContent := make([]byte, 8193)
|
||||
for i := range longContent {
|
||||
longContent[i] = 'x'
|
||||
}
|
||||
body := map[string]interface{}{
|
||||
"scope": "global",
|
||||
"title": "Test",
|
||||
"content": string(longContent),
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("POST", "/instructions", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsCreate_TitleTooLong(t *testing.T) {
|
||||
_, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.POST("/instructions", h.Create)
|
||||
|
||||
// Title > 200 chars
|
||||
longTitle := make([]byte, 201)
|
||||
for i := range longTitle {
|
||||
longTitle[i] = 'x'
|
||||
}
|
||||
body := map[string]interface{}{
|
||||
"scope": "global",
|
||||
"title": string(longTitle),
|
||||
"content": "Test",
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("POST", "/instructions", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsCreate_InsertError(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.POST("/instructions", h.Create)
|
||||
|
||||
mock.ExpectQuery(`INSERT INTO platform_instructions`).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
body := map[string]interface{}{
|
||||
"scope": "global",
|
||||
"title": "Test",
|
||||
"content": "Test",
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("POST", "/instructions", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Update ----------
|
||||
|
||||
func TestInstructionsUpdate_HappyPath(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.PUT("/instructions/:id", h.Update)
|
||||
|
||||
mock.ExpectExec(`UPDATE platform_instructions SET`).
|
||||
WithArgs("New Title", "New Content", sqlmock.AnyArg(), sqlmock.AnyArg(), "inst-123").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
body := map[string]interface{}{
|
||||
"title": "New Title",
|
||||
"content": "New Content",
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PUT", "/instructions/inst-123", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsUpdate_PartialUpdate(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.PUT("/instructions/:id", h.Update)
|
||||
|
||||
// Only title update — content/priority/enabled stay nil
|
||||
mock.ExpectExec(`UPDATE platform_instructions SET`).
|
||||
WithArgs("Only Title", sqlmock.NilArg(), sqlmock.NilArg(), sqlmock.NilArg(), "inst-123").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
body := map[string]interface{}{
|
||||
"title": "Only Title",
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PUT", "/instructions/inst-123", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsUpdate_ContentTooLong(t *testing.T) {
|
||||
_, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.PUT("/instructions/:id", h.Update)
|
||||
|
||||
longContent := make([]byte, 8193)
|
||||
for i := range longContent {
|
||||
longContent[i] = 'x'
|
||||
}
|
||||
body := map[string]interface{}{
|
||||
"content": string(longContent),
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PUT", "/instructions/inst-123", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsUpdate_TitleTooLong(t *testing.T) {
|
||||
_, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.PUT("/instructions/:id", h.Update)
|
||||
|
||||
longTitle := make([]byte, 201)
|
||||
for i := range longTitle {
|
||||
longTitle[i] = 'x'
|
||||
}
|
||||
body := map[string]interface{}{
|
||||
"title": string(longTitle),
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PUT", "/instructions/inst-123", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsUpdate_NotFound(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.PUT("/instructions/:id", h.Update)
|
||||
|
||||
mock.ExpectExec(`UPDATE platform_instructions SET`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0)) // 0 rows affected
|
||||
|
||||
body := map[string]interface{}{
|
||||
"title": "New Title",
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PUT", "/instructions/nonexistent", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsUpdate_UpdateError(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.PUT("/instructions/:id", h.Update)
|
||||
|
||||
mock.ExpectExec(`UPDATE platform_instructions SET`).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
body := map[string]interface{}{
|
||||
"title": "New Title",
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PUT", "/instructions/inst-123", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Delete ----------
|
||||
|
||||
func TestInstructionsDelete_HappyPath(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.DELETE("/instructions/:id", h.Delete)
|
||||
|
||||
mock.ExpectExec(`DELETE FROM platform_instructions WHERE id = \$1`).
|
||||
WithArgs("inst-123").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
req, _ := http.NewRequest("DELETE", "/instructions/inst-123", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsDelete_NotFound(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.DELETE("/instructions/:id", h.Delete)
|
||||
|
||||
mock.ExpectExec(`DELETE FROM platform_instructions WHERE id = \$1`).
|
||||
WithArgs("nonexistent").
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
|
||||
req, _ := http.NewRequest("DELETE", "/instructions/nonexistent", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsDelete_DeleteError(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.DELETE("/instructions/:id", h.Delete)
|
||||
|
||||
mock.ExpectExec(`DELETE FROM platform_instructions WHERE id = \$1`).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
req, _ := http.NewRequest("DELETE", "/instructions/inst-123", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Resolve ----------
|
||||
|
||||
func TestInstructionsResolve_NoInstructions(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.GET("/workspaces/:id/instructions/resolve", h.Resolve)
|
||||
|
||||
mock.ExpectQuery(`SELECT scope, title, content FROM platform_instructions`).
|
||||
WithArgs("ws-uuid-123").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"scope", "title", "content"}))
|
||||
|
||||
req, _ := http.NewRequest("GET", "/workspaces/ws-uuid-123/instructions/resolve", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]string
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to unmarshal response: %v", err)
|
||||
}
|
||||
if resp["workspace_id"] != "ws-uuid-123" {
|
||||
t.Errorf("expected workspace_id ws-uuid-123, got %s", resp["workspace_id"])
|
||||
}
|
||||
if resp["instructions"] != "" {
|
||||
t.Errorf("expected empty instructions, got %q", resp["instructions"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsResolve_GlobalOnly(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.GET("/workspaces/:id/instructions/resolve", h.Resolve)
|
||||
|
||||
mock.ExpectQuery(`SELECT scope, title, content FROM platform_instructions`).
|
||||
WithArgs("ws-uuid-123").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"scope", "title", "content"}).
|
||||
AddRow("global", "Be Nice", "Always be nice to users"))
|
||||
|
||||
req, _ := http.NewRequest("GET", "/workspaces/ws-uuid-123/instructions/resolve", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]string
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to unmarshal response: %v", err)
|
||||
}
|
||||
if resp["instructions"] == "" {
|
||||
t.Error("expected non-empty instructions")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsResolve_GlobalPlusWorkspace(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.GET("/workspaces/:id/instructions/resolve", h.Resolve)
|
||||
|
||||
mock.ExpectQuery(`SELECT scope, title, content FROM platform_instructions`).
|
||||
WithArgs("ws-uuid-123").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"scope", "title", "content"}).
|
||||
AddRow("global", "Be Nice", "Global rule content").
|
||||
AddRow("workspace", "Use Dark Mode", "WS specific rule"))
|
||||
|
||||
req, _ := http.NewRequest("GET", "/workspaces/ws-uuid-123/instructions/resolve", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]string
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to unmarshal response: %v", err)
|
||||
}
|
||||
// Both scopes should be present
|
||||
if !bytes.Contains([]byte(resp["instructions"]), []byte("Platform-Wide Rules")) {
|
||||
t.Error("expected Platform-Wide Rules section")
|
||||
}
|
||||
if !bytes.Contains([]byte(resp["instructions"]), []byte("Role-Specific Rules")) {
|
||||
t.Error("expected Role-Specific Rules section")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsResolve_QueryError(t *testing.T) {
|
||||
mock, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.GET("/workspaces/:id/instructions/resolve", h.Resolve)
|
||||
|
||||
mock.ExpectQuery(`SELECT scope, title, content FROM platform_instructions`).
|
||||
WithArgs("ws-uuid-123").
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
req, _ := http.NewRequest("GET", "/workspaces/ws-uuid-123/instructions/resolve", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstructionsResolve_MissingWorkspaceID(t *testing.T) {
|
||||
_, r := setupInstructionsTestDB(t)
|
||||
h := NewInstructionsHandler()
|
||||
r.GET("/workspaces/:id/instructions/resolve", h.Resolve)
|
||||
|
||||
// Empty workspace ID
|
||||
req, _ := http.NewRequest("GET", "/workspaces//instructions/resolve", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
// Gin will return 404 for empty path segment
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- scanInstructions helper ----------
|
||||
|
||||
func TestScanInstructions_EmptyRows(t *testing.T) {
|
||||
rows := sqlmock.NewRows([]string{"id", "scope", "scope_target", "title", "content", "priority", "enabled", "created_at", "updated_at"})
|
||||
result := scanInstructions(rows)
|
||||
if len(result) != 0 {
|
||||
t.Errorf("expected 0, got %d", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanInstructions_ScanError(t *testing.T) {
|
||||
// Rows that error on scan — scanInstructions should skip bad rows and continue
|
||||
rows := sqlmock.NewRows([]string{"id", "scope", "scope_target", "title", "content", "priority", "enabled", "created_at", "updated_at"}).
|
||||
AddRow("inst-1", "global", nil, "Good", "Good content", 10, true, "2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z").
|
||||
RowError(1, sql.ErrConnDone) // Error on second row
|
||||
result := scanInstructions(rows)
|
||||
// Should return first row, skip second
|
||||
if len(result) != 1 {
|
||||
t.Errorf("expected 1 (skipped bad row), got %d", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Helper ----------
|
||||
|
||||
func stringPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package handlers
|
||||
|
||||
// org_layout_test.go — unit coverage for org canvas layout helpers
|
||||
// (org.go). These functions compute canvas node positions and subtree
|
||||
// bounding boxes; they are pure (no DB calls, no side effects).
|
||||
//
|
||||
// Coverage targets:
|
||||
// - childSlot: 2-column grid x,y for 0th..Nth child
|
||||
// - sizeOfSubtree: leaf, single child, multi-child, deep nesting
|
||||
// - childSlotInGrid: empty siblings, uniform sizes, variable sizes,
|
||||
// index boundaries
|
||||
|
||||
import "testing"
|
||||
|
||||
// ---------- childSlot ----------
|
||||
|
||||
func TestChildSlot_FirstChild(t *testing.T) {
|
||||
x, y := childSlot(0)
|
||||
// col=0, row=0; x=parentSidePadding=16, y=parentHeaderPadding=130
|
||||
if x != 16.0 {
|
||||
t.Errorf("x = %v; want 16.0", x)
|
||||
}
|
||||
if y != 130.0 {
|
||||
t.Errorf("y = %v; want 130.0", y)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildSlot_SecondChild(t *testing.T) {
|
||||
x, y := childSlot(1)
|
||||
// col=1, row=0; x=16+(240+14)=270, y=130
|
||||
if x != 270.0 {
|
||||
t.Errorf("x = %v; want 270.0", x)
|
||||
}
|
||||
if y != 130.0 {
|
||||
t.Errorf("y = %v; want 130.0", y)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildSlot_ThirdChild(t *testing.T) {
|
||||
x, y := childSlot(2)
|
||||
// col=0, row=1; x=16, y=130+(130+14)=274
|
||||
if x != 16.0 {
|
||||
t.Errorf("x = %v; want 16.0", x)
|
||||
}
|
||||
if y != 274.0 {
|
||||
t.Errorf("y = %v; want 274.0", y)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildSlot_FourthChild(t *testing.T) {
|
||||
x, y := childSlot(3)
|
||||
// col=1, row=1; x=270, y=274
|
||||
if x != 270.0 {
|
||||
t.Errorf("x = %v; want 270.0", x)
|
||||
}
|
||||
if y != 274.0 {
|
||||
t.Errorf("y = %v; want 274.0", y)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- sizeOfSubtree ----------
|
||||
|
||||
func TestSizeOfSubtree_Leaf(t *testing.T) {
|
||||
ws := OrgWorkspace{Name: "leaf"}
|
||||
size := sizeOfSubtree(ws)
|
||||
if size.width != 240.0 {
|
||||
t.Errorf("width = %v; want 240.0", size.width)
|
||||
}
|
||||
if size.height != 130.0 {
|
||||
t.Errorf("height = %v; want 130.0", size.height)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSizeOfSubtree_SingleChild(t *testing.T) {
|
||||
ws := OrgWorkspace{
|
||||
Name: "parent",
|
||||
Children: []OrgWorkspace{{Name: "child"}},
|
||||
}
|
||||
size := sizeOfSubtree(ws)
|
||||
// cols = min(1,1) = 1; rows = 1
|
||||
// maxColW = 240 (child default)
|
||||
// width = 16*2 + 240*1 + 14*0 = 272
|
||||
// height = 130 + 130 + 14*0 + 16 = 276
|
||||
if size.width != 272.0 {
|
||||
t.Errorf("width = %v; want 272.0", size.width)
|
||||
}
|
||||
if size.height != 276.0 {
|
||||
t.Errorf("height = %v; want 276.0", size.height)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSizeOfSubtree_TwoChildren(t *testing.T) {
|
||||
ws := OrgWorkspace{
|
||||
Name: "parent",
|
||||
Children: []OrgWorkspace{
|
||||
{Name: "child1"},
|
||||
{Name: "child2"},
|
||||
},
|
||||
}
|
||||
size := sizeOfSubtree(ws)
|
||||
// cols = 2; rows = 1; maxColW = 240
|
||||
// width = 16*2 + 240*2 + 14*1 = 524
|
||||
// height = 130 + 130 + 16 = 276
|
||||
if size.width != 524.0 {
|
||||
t.Errorf("width = %v; want 524.0", size.width)
|
||||
}
|
||||
if size.height != 276.0 {
|
||||
t.Errorf("height = %v; want 276.0", size.height)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSizeOfSubtree_ThreeChildren(t *testing.T) {
|
||||
ws := OrgWorkspace{
|
||||
Name: "parent",
|
||||
Children: []OrgWorkspace{
|
||||
{Name: "child1"},
|
||||
{Name: "child2"},
|
||||
{Name: "child3"},
|
||||
},
|
||||
}
|
||||
size := sizeOfSubtree(ws)
|
||||
// cols = 2 (len=3, childGridColumnCount=2, min=2); rows = 2
|
||||
// maxColW = 240
|
||||
// width = 16*2 + 240*2 + 14*1 = 524
|
||||
// height = 130 + (130*2) + 14*1 + 16 = 420
|
||||
if size.width != 524.0 {
|
||||
t.Errorf("width = %v; want 524.0", size.width)
|
||||
}
|
||||
if size.height != 420.0 {
|
||||
t.Errorf("height = %v; want 420.0", size.height)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSizeOfSubtree_DeepNesting(t *testing.T) {
|
||||
// leaf → child → parent
|
||||
grandchild := OrgWorkspace{Name: "grandchild"}
|
||||
child := OrgWorkspace{Name: "child", Children: []OrgWorkspace{grandchild}}
|
||||
parent := OrgWorkspace{Name: "parent", Children: []OrgWorkspace{child}}
|
||||
size := sizeOfSubtree(parent)
|
||||
// grandchild: 240x130
|
||||
// child: cols=1, rows=1, maxColW=240 → 272x276
|
||||
// parent: cols=1, rows=1, maxColW=272 → 304x422
|
||||
if size.width != 304.0 {
|
||||
t.Errorf("width = %v; want 304.0", size.width)
|
||||
}
|
||||
if size.height != 422.0 {
|
||||
t.Errorf("height = %v; want 422.0", size.height)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- childSlotInGrid ----------
|
||||
|
||||
func TestChildSlotInGrid_EmptySiblings(t *testing.T) {
|
||||
x, y := childSlotInGrid(0, nil)
|
||||
if x != 16.0 || y != 130.0 {
|
||||
t.Errorf("empty siblings: got (%v,%v); want (16.0, 130.0)", x, y)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildSlotInGrid_EmptySlice(t *testing.T) {
|
||||
x, y := childSlotInGrid(0, []nodeSize{})
|
||||
if x != 16.0 || y != 130.0 {
|
||||
t.Errorf("empty slice: got (%v,%v); want (16.0, 130.0)", x, y)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildSlotInGrid_UniformSizes(t *testing.T) {
|
||||
sizes := []nodeSize{
|
||||
{240, 130},
|
||||
{240, 130},
|
||||
{240, 130},
|
||||
}
|
||||
// maxColW = 240; cols = 2; rows = 2
|
||||
// slot 0: col=0, row=0 → x=16, y=130
|
||||
x0, y0 := childSlotInGrid(0, sizes)
|
||||
if x0 != 16.0 || y0 != 130.0 {
|
||||
t.Errorf("slot 0: got (%v,%v); want (16.0, 130.0)", x0, y0)
|
||||
}
|
||||
// slot 1: col=1, row=0 → x=16+240+14=270, y=130
|
||||
x1, y1 := childSlotInGrid(1, sizes)
|
||||
if x1 != 270.0 || y1 != 130.0 {
|
||||
t.Errorf("slot 1: got (%v,%v); want (270.0, 130.0)", x1, y1)
|
||||
}
|
||||
// slot 2: col=0, row=1 → x=16, y=130+130+14=274
|
||||
x2, y2 := childSlotInGrid(2, sizes)
|
||||
if x2 != 16.0 || y2 != 274.0 {
|
||||
t.Errorf("slot 2: got (%v,%v); want (16.0, 274.0)", x2, y2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildSlotInGrid_VariableSizes(t *testing.T) {
|
||||
sizes := []nodeSize{
|
||||
{100, 80}, // narrow, short
|
||||
{300, 200}, // wide, tall
|
||||
{200, 150}, // medium
|
||||
}
|
||||
// maxColW = 300; cols = 2; rows = 2
|
||||
// slot 0: col=0, row=0 → x=16, y=130
|
||||
x0, y0 := childSlotInGrid(0, sizes)
|
||||
if x0 != 16.0 || y0 != 130.0 {
|
||||
t.Errorf("slot 0: got (%v,%v); want (16.0, 130.0)", x0, y0)
|
||||
}
|
||||
// slot 1: col=1, row=0 → x=16+300+14=330, y=130
|
||||
x1, y1 := childSlotInGrid(1, sizes)
|
||||
if x1 != 330.0 || y1 != 130.0 {
|
||||
t.Errorf("slot 1: got (%v,%v); want (330.0, 130.0)", x1, y1)
|
||||
}
|
||||
// slot 2: col=0, row=1 → x=16, y=130+200+14=344
|
||||
x2, y2 := childSlotInGrid(2, sizes)
|
||||
if x2 != 16.0 || y2 != 344.0 {
|
||||
t.Errorf("slot 2: got (%v,%v); want (16.0, 344.0)", x2, y2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildSlotInGrid_SingleChild(t *testing.T) {
|
||||
sizes := []nodeSize{{400, 300}}
|
||||
x, y := childSlotInGrid(0, sizes)
|
||||
// cols = 1 (len < 2), maxColW = 400
|
||||
// x = 16 + 0*(400+14) = 16, y = 130
|
||||
if x != 16.0 || y != 130.0 {
|
||||
t.Errorf("single child: got (%v,%v); want (16.0, 130.0)", x, y)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildSlotInGrid_LastSlot(t *testing.T) {
|
||||
sizes := []nodeSize{{200, 100}, {200, 100}, {200, 100}}
|
||||
// cols = 2, rows = 2, maxColW = 200
|
||||
// slot 2: col=0, row=1 → x=16, y=130+100+14=244
|
||||
x, y := childSlotInGrid(2, sizes)
|
||||
if x != 16.0 || y != 244.0 {
|
||||
t.Errorf("last slot: got (%v,%v); want (16.0, 244.0)", x, y)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildSlotInGrid_OverflowIndex(t *testing.T) {
|
||||
sizes := []nodeSize{{200, 100}}
|
||||
// Index beyond array bounds — Go handles this without panic
|
||||
x, y := childSlotInGrid(5, sizes)
|
||||
// col = 5 % 2 = 1, row = 5 / 2 = 2
|
||||
// x = 16 + 1*(200+14) = 230, y = 130 + 2*(100+14) = 358
|
||||
if x != 230.0 || y != 358.0 {
|
||||
t.Errorf("overflow index: got (%v,%v); want (230.0, 358.0)", x, y)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,590 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// workspace_crud_test.go — unit coverage for workspace state, update, and delete
|
||||
// handlers (workspace_crud.go), plus field validation helpers.
|
||||
//
|
||||
// Coverage targets:
|
||||
// - State: legacy (no live token), live token + valid, missing token,
|
||||
// invalid token, not found, soft-deleted, query error.
|
||||
// - Update: happy path, invalid UUID, invalid body, not found, each field
|
||||
// update, workspace_dir validation, length limits, YAML special chars.
|
||||
// - Delete: happy path, invalid UUID, has children (409), cascade delete
|
||||
// stop errors, purge path.
|
||||
// - validateWorkspaceID: valid/invalid UUID.
|
||||
// - validateWorkspaceFields: newline rejection, YAML special chars, length.
|
||||
// - validateWorkspaceDir: absolute/relative, traversal, system paths.
|
||||
|
||||
func setupWorkspaceCrudTest(t *testing.T) (sqlmock.Sqlmock, *gin.Engine) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupTestDB(t)
|
||||
r := gin.New()
|
||||
return mock, r
|
||||
}
|
||||
|
||||
// ---------- State ----------
|
||||
|
||||
func TestState_LegacyWorkspaceNoLiveToken(t *testing.T) {
|
||||
mock, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.GET("/workspaces/:id/state", h.State)
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
// No live token — legacy workspace, no auth required
|
||||
mock.ExpectQuery(`SELECT status FROM workspaces WHERE id = \$1`).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"status"}).AddRow("running"))
|
||||
|
||||
req, _ := http.NewRequest("GET", "/workspaces/"+wsID+"/state", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to unmarshal: %v", err)
|
||||
}
|
||||
if resp["workspace_id"] != wsID {
|
||||
t.Errorf("workspace_id mismatch")
|
||||
}
|
||||
if resp["status"] != "running" {
|
||||
t.Errorf("status mismatch: got %v", resp["status"])
|
||||
}
|
||||
if resp["deleted"] != false {
|
||||
t.Errorf("deleted should be false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestState_HasLiveTokenMissingAuth(t *testing.T) {
|
||||
mock, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.GET("/workspaces/:id/state", h.State)
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(`SELECT EXISTS\(SELECT 1 FROM workspace_auth_tokens`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
|
||||
req, _ := http.NewRequest("GET", "/workspaces/"+wsID+"/state", nil)
|
||||
// No Authorization header
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestState_WorkspaceNotFound(t *testing.T) {
|
||||
mock, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.GET("/workspaces/:id/state", h.State)
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(`SELECT EXISTS\(SELECT 1 FROM workspace_auth_tokens`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
mock.ExpectQuery(`SELECT status FROM workspaces WHERE id = \$1`).
|
||||
WithArgs(wsID).
|
||||
WillReturnError(sql.ErrNoRows)
|
||||
|
||||
req, _ := http.NewRequest("GET", "/workspaces/"+wsID+"/state", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404, got %d", w.Code)
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to unmarshal: %v", err)
|
||||
}
|
||||
if resp["deleted"] != true {
|
||||
t.Errorf("deleted should be true for not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestState_WorkspaceSoftDeleted(t *testing.T) {
|
||||
mock, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.GET("/workspaces/:id/state", h.State)
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(`SELECT EXISTS\(SELECT 1 FROM workspace_auth_tokens`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
mock.ExpectQuery(`SELECT status FROM workspaces WHERE id = \$1`).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"status"}).AddRow("removed"))
|
||||
|
||||
req, _ := http.NewRequest("GET", "/workspaces/"+wsID+"/state", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404 for soft-deleted, got %d", w.Code)
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to unmarshal: %v", err)
|
||||
}
|
||||
if resp["deleted"] != true {
|
||||
t.Errorf("deleted should be true")
|
||||
}
|
||||
if resp["status"] != "removed" {
|
||||
t.Errorf("status should be removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestState_QueryError(t *testing.T) {
|
||||
mock, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.GET("/workspaces/:id/state", h.State)
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(`SELECT EXISTS\(SELECT 1 FROM workspace_auth_tokens`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
mock.ExpectQuery(`SELECT status FROM workspaces WHERE id = \$1`).
|
||||
WithArgs(wsID).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
req, _ := http.NewRequest("GET", "/workspaces/"+wsID+"/state", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Update ----------
|
||||
|
||||
func TestUpdate_InvalidUUID(t *testing.T) {
|
||||
_, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.PATCH("/workspaces/:id", h.Update)
|
||||
|
||||
body := map[string]interface{}{"name": "Test"}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PATCH", "/workspaces/not-a-uuid", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_InvalidBody(t *testing.T) {
|
||||
_, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.PATCH("/workspaces/:id", h.Update)
|
||||
|
||||
req, _ := http.NewRequest("PATCH", "/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", bytes.NewReader([]byte("not json")))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_WorkspaceNotFound(t *testing.T) {
|
||||
mock, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.PATCH("/workspaces/:id", h.Update)
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(`SELECT EXISTS\(SELECT 1 FROM workspaces WHERE id = \$1\)`).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
|
||||
body := map[string]interface{}{"name": "New Name"}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PATCH", "/workspaces/"+wsID, bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_NameTooLong(t *testing.T) {
|
||||
_, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.PATCH("/workspaces/:id", h.Update)
|
||||
|
||||
longName := make([]byte, 256)
|
||||
for i := range longName {
|
||||
longName[i] = 'x'
|
||||
}
|
||||
body := map[string]interface{}{"name": string(longName)}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PATCH", "/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400 for name too long, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_RoleTooLong(t *testing.T) {
|
||||
_, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.PATCH("/workspaces/:id", h.Update)
|
||||
|
||||
longRole := make([]byte, 1001)
|
||||
for i := range longRole {
|
||||
longRole[i] = 'x'
|
||||
}
|
||||
body := map[string]interface{}{"role": string(longRole)}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PATCH", "/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400 for role too long, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_NameWithNewline(t *testing.T) {
|
||||
_, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.PATCH("/workspaces/:id", h.Update)
|
||||
|
||||
body := map[string]interface{}{"name": "Name\nwith newline"}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PATCH", "/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400 for newline in name, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_NameWithYAMLSpecialChars(t *testing.T) {
|
||||
_, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.PATCH("/workspaces/:id", h.Update)
|
||||
|
||||
body := map[string]interface{}{"name": "Name with [brackets]"}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PATCH", "/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400 for YAML special chars in name, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_WorkspaceDirSystemPath(t *testing.T) {
|
||||
_, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.PATCH("/workspaces/:id", h.Update)
|
||||
|
||||
body := map[string]interface{}{"workspace_dir": "/etc/my-workspace"}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PATCH", "/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400 for system path workspace_dir, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_WorkspaceDirTraversal(t *testing.T) {
|
||||
_, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.PATCH("/workspaces/:id", h.Update)
|
||||
|
||||
body := map[string]interface{}{"workspace_dir": "/workspace/../../../etc"}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PATCH", "/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400 for traversal in workspace_dir, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_WorkspaceDirRelativePath(t *testing.T) {
|
||||
_, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.PATCH("/workspaces/:id", h.Update)
|
||||
|
||||
body := map[string]interface{}{"workspace_dir": "relative/path"}
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest("PATCH", "/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400 for relative workspace_dir, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Delete ----------
|
||||
|
||||
func TestDelete_InvalidUUID(t *testing.T) {
|
||||
_, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.DELETE("/workspaces/:id", h.Delete)
|
||||
|
||||
req, _ := http.NewRequest("DELETE", "/workspaces/not-a-uuid", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelete_HasChildrenWithoutConfirm(t *testing.T) {
|
||||
mock, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.DELETE("/workspaces/:id", h.Delete)
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(`SELECT id, name FROM workspaces WHERE parent_id = \$1 AND status != 'removed'`).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "name"}).
|
||||
AddRow("child-1", "Child Workspace"))
|
||||
|
||||
req, _ := http.NewRequest("DELETE", "/workspaces/"+wsID, nil)
|
||||
// No ?confirm=true
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Errorf("expected 409, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to unmarshal: %v", err)
|
||||
}
|
||||
if resp["status"] != "confirmation_required" {
|
||||
t.Errorf("status should be confirmation_required")
|
||||
}
|
||||
if resp["children_count"] != float64(1) {
|
||||
t.Errorf("children_count should be 1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelete_ChildrenCheckQueryError(t *testing.T) {
|
||||
mock, r := setupWorkspaceCrudTest(t)
|
||||
h := NewWorkspaceHandler(nil, nil, nil, nil)
|
||||
r.DELETE("/workspaces/:id", h.Delete)
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(`SELECT id, name FROM workspaces WHERE parent_id = \$1 AND status != 'removed'`).
|
||||
WithArgs(wsID).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
req, _ := http.NewRequest("DELETE", "/workspaces/"+wsID, nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- validateWorkspaceID ----------
|
||||
|
||||
func TestValidateWorkspaceID_Valid(t *testing.T) {
|
||||
err := validateWorkspaceID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
|
||||
if err != nil {
|
||||
t.Errorf("expected nil, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceID_Invalid(t *testing.T) {
|
||||
err := validateWorkspaceID("not-a-uuid")
|
||||
if err == nil {
|
||||
t.Error("expected error for invalid UUID")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- validateWorkspaceFields ----------
|
||||
|
||||
func TestValidateWorkspaceFields_NewlineInName(t *testing.T) {
|
||||
err := validateWorkspaceFields("name\nwith\nnewline", "", "", "")
|
||||
if err == nil {
|
||||
t.Error("expected error for newline in name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceFields_NewlineInRole(t *testing.T) {
|
||||
err := validateWorkspaceFields("", "role\rwith\rcarriage", "", "")
|
||||
if err == nil {
|
||||
t.Error("expected error for carriage return in role")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceFields_YAMLSpecialCharsInName(t *testing.T) {
|
||||
for _, ch := range "{}[]|>*&!" {
|
||||
err := validateWorkspaceFields("namewith"+string(ch), "", "", "")
|
||||
if err == nil {
|
||||
t.Errorf("expected error for YAML special char %c in name", ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceFields_NameTooLong(t *testing.T) {
|
||||
longName := make([]byte, 256)
|
||||
for i := range longName {
|
||||
longName[i] = 'x'
|
||||
}
|
||||
err := validateWorkspaceFields(string(longName), "", "", "")
|
||||
if err == nil {
|
||||
t.Error("expected error for name > 255 chars")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceFields_RoleTooLong(t *testing.T) {
|
||||
longRole := make([]byte, 1001)
|
||||
for i := range longRole {
|
||||
longRole[i] = 'x'
|
||||
}
|
||||
err := validateWorkspaceFields("", string(longRole), "", "")
|
||||
if err == nil {
|
||||
t.Error("expected error for role > 1000 chars")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceFields_Valid(t *testing.T) {
|
||||
err := validateWorkspaceFields("ValidName", "ValidRole", "gpt-4", "claude")
|
||||
if err != nil {
|
||||
t.Errorf("expected nil, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- validateWorkspaceDir ----------
|
||||
|
||||
func TestValidateWorkspaceDir_Valid(t *testing.T) {
|
||||
err := validateWorkspaceDir("/workspace/my-workspace")
|
||||
if err != nil {
|
||||
t.Errorf("expected nil, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceDir_RelativePath(t *testing.T) {
|
||||
err := validateWorkspaceDir("relative/path")
|
||||
if err == nil {
|
||||
t.Error("expected error for relative path")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceDir_Traversal(t *testing.T) {
|
||||
err := validateWorkspaceDir("/workspace/../etc")
|
||||
if err == nil {
|
||||
t.Error("expected error for traversal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceDir_SystemPathEtc(t *testing.T) {
|
||||
for _, path := range []string{"/etc", "/var", "/proc", "/sys", "/dev", "/boot", "/sbin", "/bin", "/lib", "/usr"} {
|
||||
err := validateWorkspaceDir(path)
|
||||
if err == nil {
|
||||
t.Errorf("expected error for system path %s", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceDir_SystemPathPrefix(t *testing.T) {
|
||||
err := validateWorkspaceDir("/etc/something")
|
||||
if err == nil {
|
||||
t.Error("expected error for /etc/something")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceDir_Empty(t *testing.T) {
|
||||
err := validateWorkspaceDir("")
|
||||
if err == nil {
|
||||
t.Error("expected error for empty path")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- CascadeDelete ----------
|
||||
|
||||
func TestCascadeDelete_InvalidUUID(t *testing.T) {
|
||||
h := &WorkspaceHandler{}
|
||||
descendants, stopErrs, err := h.CascadeDelete(context.Background(), "not-a-uuid")
|
||||
if err == nil {
|
||||
t.Error("expected error for invalid UUID")
|
||||
}
|
||||
if descendants != nil || stopErrs != nil {
|
||||
t.Error("expected nil returns on error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCascadeDelete_DescendantQueryError(t *testing.T) {
|
||||
mock, r := setupWorkspaceCrudTest(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
_ = r
|
||||
|
||||
// CascadeDelete returns early on descendant query error — nil deps for
|
||||
// StopWorkspace/RemoveVolume/broadcaster are fine since they are never
|
||||
// reached in this error path.
|
||||
h := &WorkspaceHandler{}
|
||||
// Note: the descendant CTE query is called with zero args (workspace ID
|
||||
// is embedded in the query string, not passed as a query arg).
|
||||
mock.ExpectQuery(`WITH RECURSIVE descendants AS`).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
deleted, stopErrs, err := h.CascadeDelete(context.Background(), wsID)
|
||||
if err == nil {
|
||||
t.Error("CascadeDelete returned nil error; want descendant query error")
|
||||
}
|
||||
if deleted != nil {
|
||||
t.Errorf("deleted = %v; want nil", deleted)
|
||||
}
|
||||
if stopErrs != nil {
|
||||
t.Errorf("stopErrs = %v; want nil", stopErrs)
|
||||
}
|
||||
// sqlmock verifies all expected queries were executed
|
||||
}
|
||||
|
||||
// Note: Full CascadeDelete testing requires mocking StopWorkspace, RemoveVolume,
|
||||
// and provisioner calls — covered in integration tests. Unit tests here focus on
|
||||
// the validation and pre-condition paths.
|
||||
@@ -0,0 +1,248 @@
|
||||
package ws
|
||||
|
||||
// hub_test.go — unit coverage for the WebSocket hub (hub.go).
|
||||
//
|
||||
// Coverage targets:
|
||||
// - NewHub: initial state (clients empty, channels created, done not closed)
|
||||
// - safeSend: sends to open channel, closed channel, full buffer
|
||||
// - Broadcast: canvas client (no workspace ID) gets all messages,
|
||||
// workspace client gets message only when CanCommunicate returns true,
|
||||
// drops on closed/full channel
|
||||
// - Close: idempotent (closeOnce), disconnects all clients, closes done
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Molecule-AI/molecule-monorepo/platform/internal/models"
|
||||
)
|
||||
|
||||
// ---------- NewHub ----------
|
||||
|
||||
func TestNewHub(t *testing.T) {
|
||||
h := NewHub(nil)
|
||||
if h == nil {
|
||||
t.Fatal("NewHub returned nil")
|
||||
}
|
||||
if len(h.clients) != 0 {
|
||||
t.Errorf("new hub has %d clients; want 0", len(h.clients))
|
||||
}
|
||||
if h.Register == nil {
|
||||
t.Error("Register channel is nil")
|
||||
}
|
||||
if h.Unregister == nil {
|
||||
t.Error("Unregister channel is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewHub_WithAccessChecker(t *testing.T) {
|
||||
called := false
|
||||
checker := func(callerID, targetID string) bool {
|
||||
called = true
|
||||
return callerID == targetID
|
||||
}
|
||||
h := NewHub(checker)
|
||||
if h.canCommunicate == nil {
|
||||
t.Fatal("canCommunicate is nil")
|
||||
}
|
||||
if !h.canCommunicate("ws-1", "ws-1") {
|
||||
t.Error("canCommunicate should return true for same ID")
|
||||
}
|
||||
if h.canCommunicate("ws-1", "ws-2") {
|
||||
t.Error("canCommunicate should return false for different IDs")
|
||||
}
|
||||
// Verify the checker was invoked at least once
|
||||
if !called {
|
||||
t.Error("access checker was not called")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- safeSend ----------
|
||||
|
||||
func TestSafeSend_OpenChannel(t *testing.T) {
|
||||
ch := make(chan []byte, 1)
|
||||
client := &Client{Send: ch}
|
||||
got := safeSend(client, []byte("hello"))
|
||||
if !got {
|
||||
t.Error("safeSend returned false for open channel")
|
||||
}
|
||||
if len(ch) != 1 {
|
||||
t.Errorf("channel has %d messages; want 1", len(ch))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeSend_ClosedChannel(t *testing.T) {
|
||||
ch := make(chan []byte)
|
||||
close(ch)
|
||||
client := &Client{Send: ch}
|
||||
got := safeSend(client, []byte("hello"))
|
||||
if got {
|
||||
t.Error("safeSend returned true for closed channel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeSend_FullChannel(t *testing.T) {
|
||||
ch := make(chan []byte, 1)
|
||||
ch <- []byte("already full")
|
||||
client := &Client{Send: ch}
|
||||
got := safeSend(client, []byte("second"))
|
||||
if got {
|
||||
t.Error("safeSend returned true for full channel")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Broadcast ----------
|
||||
|
||||
func TestBroadcast_CanvasClientGetsAll(t *testing.T) {
|
||||
ch := make(chan []byte, 10)
|
||||
client := &Client{WorkspaceID: "", Send: ch}
|
||||
h := NewHub(nil)
|
||||
h.clients = map[*Client]bool{client: true}
|
||||
|
||||
h.Broadcast(models.WSMessage{Event: "test"})
|
||||
<-ch // non-blocking since channel has capacity
|
||||
}
|
||||
|
||||
func TestBroadcast_WorkspaceClientGetsWhenAllowed(t *testing.T) {
|
||||
ch := make(chan []byte, 10)
|
||||
client := &Client{WorkspaceID: "ws-caller", Send: ch}
|
||||
allowed := false
|
||||
h := NewHub(func(callerID, targetID string) bool {
|
||||
return allowed
|
||||
})
|
||||
msg := models.WSMessage{Event: "test", WorkspaceID: "ws-target"}
|
||||
h.clients = map[*Client]bool{client: true}
|
||||
|
||||
// Not allowed — should not receive
|
||||
h.Broadcast(msg)
|
||||
if len(ch) != 0 {
|
||||
t.Errorf("disallowed client received %d messages; want 0", len(ch))
|
||||
}
|
||||
|
||||
// Now allow
|
||||
allowed = true
|
||||
h.Broadcast(msg)
|
||||
if len(ch) != 1 {
|
||||
t.Errorf("allowed client received %d messages; want 1", len(ch))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_DropsOnClosedChannel(t *testing.T) {
|
||||
// Use a named variable for the client so the map key and Broadcast's
|
||||
// range both refer to the same *Client pointer.
|
||||
ch := make(chan []byte, 1)
|
||||
client := &Client{WorkspaceID: "", Send: ch}
|
||||
h := NewHub(nil)
|
||||
h.clients = map[*Client]bool{client: true}
|
||||
|
||||
// Fill and close so any subsequent send (from Broadcast) hits
|
||||
// safeSend's default → returns false without blocking or panicking.
|
||||
ch <- []byte("fill")
|
||||
close(ch)
|
||||
|
||||
// Broadcast must not panic — safeSend returns false for closed channel
|
||||
h.Broadcast(models.WSMessage{Event: "test"})
|
||||
}
|
||||
|
||||
func TestBroadcast_EmptyHub(t *testing.T) {
|
||||
h := NewHub(nil)
|
||||
// Broadcast to empty hub should not panic
|
||||
h.Broadcast(models.WSMessage{Event: "test"})
|
||||
}
|
||||
|
||||
func TestBroadcast_MultipleClients(t *testing.T) {
|
||||
ch1 := make(chan []byte, 10)
|
||||
ch2 := make(chan []byte, 10)
|
||||
ch3 := make(chan []byte, 10) // disallowed
|
||||
c1 := &Client{WorkspaceID: "ws-1", Send: ch1}
|
||||
c2 := &Client{WorkspaceID: "ws-2", Send: ch2}
|
||||
c3 := &Client{WorkspaceID: "ws-3", Send: ch3}
|
||||
h := NewHub(func(callerID, targetID string) bool {
|
||||
return targetID != "ws-3"
|
||||
})
|
||||
msg := models.WSMessage{Event: "test", WorkspaceID: "ws-target"}
|
||||
h.clients = map[*Client]bool{c1: true, c2: true, c3: true}
|
||||
|
||||
h.Broadcast(msg)
|
||||
|
||||
select {
|
||||
case <-ch1:
|
||||
// received
|
||||
default:
|
||||
t.Error("ws-1 should have received message")
|
||||
}
|
||||
select {
|
||||
case <-ch2:
|
||||
// received
|
||||
default:
|
||||
t.Error("ws-2 should have received message")
|
||||
}
|
||||
select {
|
||||
case <-ch3:
|
||||
t.Error("ws-3 should NOT have received message")
|
||||
default:
|
||||
// correct — ws-3 is disallowed
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_CanvasClientAlwaysGets(t *testing.T) {
|
||||
ch := make(chan []byte, 10)
|
||||
canvasClient := &Client{WorkspaceID: "", Send: ch}
|
||||
h := NewHub(func(callerID, targetID string) bool {
|
||||
return false // nobody can communicate with anybody
|
||||
})
|
||||
msg := models.WSMessage{Event: "test", WorkspaceID: "ws-target"}
|
||||
h.clients = map[*Client]bool{
|
||||
canvasClient: true, // canvas client
|
||||
&Client{WorkspaceID: "ws-target", Send: make(chan []byte, 10)}: true,
|
||||
}
|
||||
|
||||
h.Broadcast(msg)
|
||||
|
||||
select {
|
||||
case <-ch:
|
||||
// received
|
||||
default:
|
||||
t.Error("canvas client should always receive messages regardless of CanCommunicate")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Close ----------
|
||||
|
||||
func TestClose_DisconnectsClients(t *testing.T) {
|
||||
ch1 := make(chan []byte, 1)
|
||||
ch2 := make(chan []byte, 1)
|
||||
h := NewHub(nil)
|
||||
h.clients = map[*Client]bool{
|
||||
{Send: ch1}: true,
|
||||
{Send: ch2}: true,
|
||||
}
|
||||
|
||||
h.Close()
|
||||
|
||||
if len(h.clients) != 0 {
|
||||
t.Errorf("after Close, %d clients remain; want 0", len(h.clients))
|
||||
}
|
||||
}
|
||||
|
||||
func TestClose_Idempotent(t *testing.T) {
|
||||
ch := make(chan []byte, 1)
|
||||
h := NewHub(nil)
|
||||
h.clients = map[*Client]bool{{Send: ch}: true}
|
||||
|
||||
// Should not panic on second call (closeOnce)
|
||||
h.Close()
|
||||
h.Close()
|
||||
h.Close()
|
||||
}
|
||||
|
||||
func TestClose_DoneChannelClosed(t *testing.T) {
|
||||
h := NewHub(nil)
|
||||
h.Close()
|
||||
|
||||
select {
|
||||
case <-h.done:
|
||||
// done is closed — correct
|
||||
default:
|
||||
t.Error("done channel should be closed after Close")
|
||||
}
|
||||
}
|
||||
+7
-148
@@ -12,14 +12,12 @@ Environment variables (set by the workspace container):
|
||||
PLATFORM_URL — platform API base URL (e.g. http://platform:8080)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
import uuid
|
||||
from typing import Callable
|
||||
|
||||
# Top-level (not inside main()) so the wheel rewriter expands this to
|
||||
@@ -767,163 +765,24 @@ async def main(): # pragma: no cover
|
||||
break
|
||||
|
||||
|
||||
# --- HTTP/SSE Transport (for Hermes runtime) ---
|
||||
|
||||
# Per-connection pending request queue.
|
||||
# Maps connection-id → asyncio.Queue of JSON-RPC responses.
|
||||
_http_connection_queues: dict[str, asyncio.Queue] = {}
|
||||
_http_connection_lock = asyncio.Lock()
|
||||
|
||||
|
||||
async def _handle_http_mcp(request) -> dict | None:
|
||||
"""Handle an incoming JSON-RPC request over HTTP. Returns the JSON-RPC response dict, or None for notifications."""
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}
|
||||
|
||||
req_id = body.get("id")
|
||||
method = body.get("method", "")
|
||||
|
||||
if method == "initialize":
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": _build_initialize_result(),
|
||||
}
|
||||
elif method == "notifications/initialized":
|
||||
return None # No response needed
|
||||
elif method == "tools/list":
|
||||
return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}}
|
||||
elif method == "tools/call":
|
||||
params = body.get("params", {})
|
||||
tool_name = params.get("name", "")
|
||||
tool_args = params.get("arguments", {})
|
||||
result_text = await handle_tool_call(tool_name, tool_args)
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {"content": [{"type": "text", "text": result_text}]},
|
||||
}
|
||||
else:
|
||||
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}}
|
||||
|
||||
|
||||
async def _run_http_server(port: int) -> None:
|
||||
"""Run MCP server over HTTP/SSE — compatible with Hermes MCP-native agents."""
|
||||
try:
|
||||
from starlette.applications import Starlette # noqa: F401
|
||||
from starlette.routing import Route # noqa: F401
|
||||
from starlette.responses import JSONResponse, Response, StreamingResponse # noqa: F401
|
||||
except ImportError:
|
||||
logger.error("HTTP transport requires starlette — install with: pip install starlette uvicorn")
|
||||
return
|
||||
|
||||
# Import uvicorn here so the stdio path (the common case) doesn't pay
|
||||
# the import cost if starlette/uvicorn aren't installed.
|
||||
import uvicorn # noqa: F401
|
||||
|
||||
_http_connection_queues.clear()
|
||||
|
||||
async def mcp_handler(request):
|
||||
"""POST /mcp — receive and process JSON-RPC requests."""
|
||||
conn_id = request.headers.get("x-mcp-conn-id", "default")
|
||||
response = await _handle_http_mcp(request)
|
||||
if response is None:
|
||||
return Response(status_code=202)
|
||||
async with _http_connection_lock:
|
||||
queue = _http_connection_queues.get(conn_id)
|
||||
if queue is not None and not queue.full():
|
||||
await queue.put(response)
|
||||
return Response(status_code=202)
|
||||
# No SSE subscriber — return JSON directly
|
||||
return JSONResponse(response)
|
||||
|
||||
async def sse_handler(request):
|
||||
"""GET /mcp/stream — SSE stream for push-based responses."""
|
||||
conn_id = str(uuid.uuid4())
|
||||
queue: asyncio.Queue = asyncio.Queue(maxsize=100)
|
||||
async with _http_connection_lock:
|
||||
_http_connection_queues[conn_id] = queue
|
||||
|
||||
async def event_stream():
|
||||
yield f"event: connected\ndata: {json.dumps({'conn_id': conn_id})}\n\n"
|
||||
try:
|
||||
while True:
|
||||
response = await asyncio.wait_for(queue.get(), timeout=300)
|
||||
yield f"event: message\ndata: {json.dumps(response)}\n\n"
|
||||
if queue.empty():
|
||||
yield "event: heartbeat\ndata: null\n\n"
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
finally:
|
||||
async with _http_connection_lock:
|
||||
_http_connection_queues.pop(conn_id, None)
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
|
||||
async def health_handler(_request):
|
||||
return JSONResponse({"ok": True, "transport": "http+sse", "port": port})
|
||||
|
||||
app = Starlette(
|
||||
routes=[
|
||||
Route("/mcp", mcp_handler, methods=["POST"]),
|
||||
Route("/mcp/stream", sse_handler, methods=["GET"]),
|
||||
Route("/health", health_handler),
|
||||
]
|
||||
)
|
||||
config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning")
|
||||
server = uvicorn.Server(config)
|
||||
logger.info(f"A2A MCP HTTP server listening on http://127.0.0.1:{port}/mcp")
|
||||
await server.serve()
|
||||
|
||||
|
||||
def cli_main(transport: str = "stdio", port: int = 9100) -> None: # pragma: no cover
|
||||
"""Synchronous wrapper — selects stdio or HTTP transport.
|
||||
def cli_main() -> None: # pragma: no cover
|
||||
"""Synchronous wrapper around the async MCP stdio loop.
|
||||
|
||||
Called by ``mcp_cli.main`` (the ``molecule-mcp`` console-script
|
||||
entry point in scripts/build_runtime_package.py) AFTER env
|
||||
validation and the standalone register + heartbeat thread setup.
|
||||
Direct callers (in-container code that already validated env and
|
||||
runs heartbeat.py separately) can also invoke this.
|
||||
runs heartbeat.py separately) can also invoke this — it's the
|
||||
smallest possible "run the MCP stdio JSON-RPC loop" surface.
|
||||
|
||||
Wheel-smoke gates in scripts/wheel_smoke.py pin the importability
|
||||
of this name (alongside ``mcp_cli.main``) so a silent rename can't
|
||||
break every external-runtime operator's MCP install — the 0.1.16
|
||||
``main_sync`` rename incident is the cautionary precedent.
|
||||
|
||||
Args:
|
||||
transport: "stdio" (default) or "http" (HTTP+SSE for Hermes).
|
||||
port: TCP port for HTTP transport (default 9100).
|
||||
"""
|
||||
if transport == "http":
|
||||
asyncio.run(_run_http_server(port))
|
||||
else:
|
||||
_assert_stdio_is_pipe_compatible()
|
||||
asyncio.run(main())
|
||||
_assert_stdio_is_pipe_compatible()
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
parser = argparse.ArgumentParser(description="A2A MCP Server")
|
||||
parser.add_argument(
|
||||
"--transport",
|
||||
default="stdio",
|
||||
choices=["stdio", "http"],
|
||||
help="Transport mode: stdio (default) or http (HTTP+SSE for Hermes)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--port",
|
||||
type=int,
|
||||
default=9100,
|
||||
help="TCP port for HTTP transport (default 9100)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
cli_main(transport=args.transport, port=args.port)
|
||||
cli_main()
|
||||
|
||||
@@ -1,671 +0,0 @@
|
||||
"""Tests for the HTTP/SSE transport of a2a_mcp_server.
|
||||
|
||||
Covers:
|
||||
- _handle_http_mcp: JSON-RPC request parsing and routing
|
||||
- Starlette app routes: POST /mcp, GET /mcp/stream, GET /health
|
||||
- cli_main argparse: --transport and --port flags
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import types
|
||||
import uuid
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _DummyRequest:
|
||||
"""Minimal request duck-type for _handle_http_mcp."""
|
||||
|
||||
def __init__(self, body_json: dict, headers: dict | None = None):
|
||||
self._body = body_json
|
||||
self.headers = headers or {}
|
||||
|
||||
async def json(self) -> dict:
|
||||
return self._body
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _handle_http_mcp — unit tests (no I/O)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_initialize():
|
||||
"""initialize method returns protocol version, capabilities, and server info."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
req = _DummyRequest({"jsonrpc": "2.0", "id": 42, "method": "initialize", "params": {}})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["jsonrpc"] == "2.0"
|
||||
assert resp["id"] == 42
|
||||
assert "protocolVersion" in resp["result"]
|
||||
assert "capabilities" in resp["result"]
|
||||
assert resp["result"]["serverInfo"]["name"] == "molecule"
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_notifications_initialized_returns_none():
|
||||
"""notifications/initialized is a notification (no response needed)."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
req = _DummyRequest({"jsonrpc": "2.0", "method": "notifications/initialized"})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_tools_list():
|
||||
"""tools/list returns the TOOLS schema."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
req = _DummyRequest({"jsonrpc": "2.0", "id": 7, "method": "tools/list"})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["jsonrpc"] == "2.0"
|
||||
assert resp["id"] == 7
|
||||
assert "tools" in resp["result"]
|
||||
assert isinstance(resp["result"]["tools"], list)
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_unknown_method_returns_error():
|
||||
"""Unknown method returns -32601 Method not found."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
req = _DummyRequest({"jsonrpc": "2.0", "id": 3, "method": "foobar", "params": {}})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["jsonrpc"] == "2.0"
|
||||
assert resp["id"] == 3
|
||||
assert resp["error"]["code"] == -32601
|
||||
assert "Method not found" in resp["error"]["message"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_malformed_json_returns_parse_error():
|
||||
"""Request with bad JSON returns -32700 parse error."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
req = _DummyRequest.__new__(_DummyRequest)
|
||||
req.headers = {}
|
||||
req.json = AsyncMock(side_effect=ValueError("bad json"))
|
||||
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["error"]["code"] == -32700
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_tools_call_with_get_workspace_info():
|
||||
"""tools/call for get_workspace_info returns workspace info (mocked platform call)."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
with patch("a2a_mcp_server.tool_get_workspace_info", AsyncMock(return_value="mocked info")):
|
||||
req = _DummyRequest({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 9,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "get_workspace_info", "arguments": {}},
|
||||
})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["jsonrpc"] == "2.0"
|
||||
assert resp["id"] == 9
|
||||
assert resp["result"]["content"][0]["text"] == "mocked info"
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_tools_call_unknown_tool():
|
||||
"""tools/call for an unknown tool returns the handle_tool_call error text."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
req = _DummyRequest({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 11,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "not_a_real_tool", "arguments": {}},
|
||||
})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["jsonrpc"] == "2.0"
|
||||
assert resp["id"] == 11
|
||||
assert "Unknown tool" in resp["result"]["content"][0]["text"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Starlette app — integration tests with TestClient
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def _clear_http_globals():
|
||||
"""Reset module-level HTTP state before and after each test."""
|
||||
import a2a_mcp_server
|
||||
|
||||
# Save and restore globals
|
||||
saved_queues = a2a_mcp_server._http_connection_queues.copy()
|
||||
saved_lock = a2a_mcp_server._http_connection_lock
|
||||
a2a_mcp_server._http_connection_queues.clear()
|
||||
yield
|
||||
# Restore
|
||||
a2a_mcp_server._http_connection_queues = saved_queues
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def _register_sse_queue():
|
||||
"""Register a queue for SSE push delivery (synchronous — callable from tests)."""
|
||||
conn_id = str(uuid.uuid4())
|
||||
queue = asyncio.Queue(maxsize=100)
|
||||
import a2a_mcp_server
|
||||
a2a_mcp_server._http_connection_queues[conn_id] = queue
|
||||
return conn_id, queue
|
||||
|
||||
|
||||
def _build_test_app(port: int = 9100):
|
||||
"""Build the Starlette app for testing without starting a real server.
|
||||
|
||||
Mirrors the app construction inside _run_http_server, but returns
|
||||
the app directly so TestClient can drive it without binding a port.
|
||||
"""
|
||||
from starlette.applications import Starlette
|
||||
from starlette.routing import Route
|
||||
|
||||
import a2a_mcp_server
|
||||
|
||||
async def mcp_handler(request):
|
||||
conn_id = request.headers.get("x-mcp-conn-id", "default")
|
||||
response = await a2a_mcp_server._handle_http_mcp(request)
|
||||
if response is None:
|
||||
from starlette.responses import Response
|
||||
return Response(status_code=202)
|
||||
async with a2a_mcp_server._http_connection_lock:
|
||||
queue = a2a_mcp_server._http_connection_queues.get(conn_id)
|
||||
if queue is not None and not queue.full():
|
||||
await queue.put(response)
|
||||
from starlette.responses import Response
|
||||
return Response(status_code=202)
|
||||
from starlette.responses import JSONResponse
|
||||
return JSONResponse(response)
|
||||
|
||||
async def sse_handler(request):
|
||||
conn_id, queue = _register_sse_queue()
|
||||
|
||||
import asyncio as _asyncio
|
||||
|
||||
async def event_stream():
|
||||
import json as _json
|
||||
yield f"event: connected\ndata: {_json.dumps({'conn_id': conn_id})}\n\n"
|
||||
try:
|
||||
while True:
|
||||
response = await _asyncio.wait_for(queue.get(), timeout=300)
|
||||
import json as _json
|
||||
yield f"event: message\ndata: {_json.dumps(response)}\n\n"
|
||||
if queue.empty():
|
||||
yield "event: heartbeat\ndata: null\n\n"
|
||||
except _asyncio.TimeoutError:
|
||||
pass
|
||||
finally:
|
||||
async with a2a_mcp_server._http_connection_lock:
|
||||
a2a_mcp_server._http_connection_queues.pop(conn_id, None)
|
||||
|
||||
from starlette.responses import StreamingResponse
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
|
||||
async def health_handler(_request):
|
||||
from starlette.responses import JSONResponse
|
||||
return JSONResponse({"ok": True, "transport": "http+sse", "port": port})
|
||||
|
||||
return Starlette(
|
||||
routes=[
|
||||
Route("/mcp", mcp_handler, methods=["POST"]),
|
||||
Route("/mcp/stream", sse_handler, methods=["GET"]),
|
||||
Route("/health", health_handler),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class TestHTTPAppRoutes:
|
||||
"""Integration tests using Starlette TestClient against the HTTP app.
|
||||
|
||||
Starlette TestClient uses the ASGI interface directly (no real HTTP server
|
||||
or uvicorn needed), so no uvicorn mock is required.
|
||||
"""
|
||||
|
||||
def test_health_returns_ok_and_transport(self, _clear_http_globals):
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
app = _build_test_app(port=9100)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get("/health")
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["ok"] is True
|
||||
assert data["transport"] == "http+sse"
|
||||
assert data["port"] == 9100
|
||||
|
||||
def test_health_accepts_different_port(self, _clear_http_globals):
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
app = _build_test_app(port=9999)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get("/health")
|
||||
|
||||
assert resp.json()["port"] == 9999
|
||||
|
||||
def test_mcp_post_initialize(self, _clear_http_globals):
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
app = _build_test_app()
|
||||
with TestClient(app) as client:
|
||||
resp = client.post("/mcp", json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {},
|
||||
})
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["id"] == 1
|
||||
assert "protocolVersion" in data["result"]
|
||||
|
||||
def test_mcp_post_tools_list(self, _clear_http_globals):
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
app = _build_test_app()
|
||||
with TestClient(app) as client:
|
||||
resp = client.post("/mcp", json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 2,
|
||||
"method": "tools/list",
|
||||
"params": {},
|
||||
})
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert "tools" in data["result"]
|
||||
assert len(data["result"]["tools"]) > 0
|
||||
|
||||
def test_mcp_post_notifications_initialized_returns_202(self, _clear_http_globals):
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
app = _build_test_app()
|
||||
with TestClient(app) as client:
|
||||
resp = client.post("/mcp", json={
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/initialized",
|
||||
})
|
||||
|
||||
# Notifications return 202 with no body
|
||||
assert resp.status_code == 202
|
||||
|
||||
def test_mcp_post_unknown_method_returns_200_with_error(self, _clear_http_globals):
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
app = _build_test_app()
|
||||
with TestClient(app) as client:
|
||||
resp = client.post("/mcp", json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 5,
|
||||
"method": "no_such_method",
|
||||
"params": {},
|
||||
})
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["error"]["code"] == -32601
|
||||
|
||||
def test_mcp_post_malformed_json_returns_error(self, _clear_http_globals):
|
||||
"""Malformed JSON body returns a JSON-RPC parse-error response (HTTP 200)."""
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
app = _build_test_app()
|
||||
with TestClient(app, raise_server_exceptions=False) as client:
|
||||
resp = client.post(
|
||||
"/mcp",
|
||||
content=b"not json at all",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
# _handle_http_mcp catches ValueError from request.json() and returns
|
||||
# a JSON-RPC parse-error response with HTTP 200.
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["error"]["code"] == -32700
|
||||
assert "Parse error" in resp.json()["error"]["message"]
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_sse_stream_populates_queue(self, _clear_http_globals):
|
||||
"""_register_sse_queue adds a queue to _http_connection_queues before any async work."""
|
||||
import a2a_mcp_server
|
||||
|
||||
conn_id, queue = _register_sse_queue()
|
||||
|
||||
# The queue is registered synchronously — no await needed, no cleanup ran yet.
|
||||
assert conn_id in a2a_mcp_server._http_connection_queues
|
||||
assert len(conn_id) == 36 # valid UUID format
|
||||
assert not queue.full()
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_sse_queue_delivers_response(self, _clear_http_globals):
|
||||
"""POST /mcp with x-mcp-conn-id routes response into the SSE queue."""
|
||||
import uuid
|
||||
|
||||
import a2a_mcp_server
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
# Pre-register an SSE queue to simulate an active SSE subscriber
|
||||
conn_id = str(uuid.uuid4())
|
||||
queue: asyncio.Queue = asyncio.Queue(maxsize=100)
|
||||
async with a2a_mcp_server._http_connection_lock:
|
||||
a2a_mcp_server._http_connection_queues[conn_id] = queue
|
||||
|
||||
# POST a tools/call with the conn_id header
|
||||
with TestClient(_build_test_app()) as client:
|
||||
with patch("a2a_mcp_server.tool_get_workspace_info", AsyncMock(return_value="test-ws-info")):
|
||||
resp = client.post(
|
||||
"/mcp",
|
||||
headers={"x-mcp-conn-id": conn_id},
|
||||
json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 99,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "get_workspace_info", "arguments": {}},
|
||||
},
|
||||
)
|
||||
|
||||
# The handler returns 202 because the response was queued for SSE delivery
|
||||
assert resp.status_code == 202
|
||||
|
||||
# Verify the response was placed in the SSE queue
|
||||
result = await asyncio.wait_for(queue.get(), timeout=2.0)
|
||||
assert result["id"] == 99
|
||||
assert result["result"]["content"][0]["text"] == "test-ws-info"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# handle_tool_call — remaining tool branches
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_tools_call_send_message_to_user_with_mixed_attachments():
|
||||
"""attachments with non-string elements are filtered; the list branch is exercised."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
with patch("a2a_mcp_server.tool_send_message_to_user", AsyncMock(return_value="sent ok")) as mock_fn:
|
||||
req = _DummyRequest({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 21,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "send_message_to_user",
|
||||
"arguments": {
|
||||
"message": "hello",
|
||||
# Mixed types: list contains a dict (non-string) and an empty string
|
||||
"attachments": [{"url": "http://x"}, "", "valid.zip", None],
|
||||
},
|
||||
},
|
||||
})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["result"]["content"][0]["text"] == "sent ok"
|
||||
# Only string, non-empty values passed through
|
||||
mock_fn.assert_called_once()
|
||||
_, kwargs = mock_fn.call_args
|
||||
assert kwargs["attachments"] == ["valid.zip"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_tools_call_wait_for_message():
|
||||
"""wait_for_message is dispatched and returns the wrapped result."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
with patch("a2a_mcp_server.tool_wait_for_message", AsyncMock(return_value="no messages")):
|
||||
req = _DummyRequest({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 22,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "wait_for_message", "arguments": {"timeout_secs": 5.0}},
|
||||
})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["result"]["content"][0]["text"] == "no messages"
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_tools_call_inbox_peek():
|
||||
"""inbox_peek is dispatched with the limit argument."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
with patch("a2a_mcp_server.tool_inbox_peek", AsyncMock(return_value="2 items")):
|
||||
req = _DummyRequest({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 23,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "inbox_peek", "arguments": {"limit": 5}},
|
||||
})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["result"]["content"][0]["text"] == "2 items"
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_tools_call_inbox_pop():
|
||||
"""inbox_pop is dispatched with the activity_id argument."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
with patch("a2a_mcp_server.tool_inbox_pop", AsyncMock(return_value="acked")):
|
||||
req = _DummyRequest({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 24,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "inbox_pop", "arguments": {"activity_id": "abc-123"}},
|
||||
})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["result"]["content"][0]["text"] == "acked"
|
||||
|
||||
|
||||
@pytest.mark.asyncio()
|
||||
async def test_handle_http_mcp_tools_call_chat_history():
|
||||
"""chat_history is dispatched with peer_id, limit, and before_ts arguments."""
|
||||
from a2a_mcp_server import _handle_http_mcp
|
||||
|
||||
with patch("a2a_mcp_server.tool_chat_history", AsyncMock(return_value="history")):
|
||||
req = _DummyRequest({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 25,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "chat_history",
|
||||
"arguments": {"peer_id": "ws-peer-1", "limit": 10, "before_ts": ""},
|
||||
},
|
||||
})
|
||||
resp = await _handle_http_mcp(req)
|
||||
|
||||
assert resp["result"]["content"][0]["text"] == "history"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# cli_main argparse — unit tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_mcp_post_falls_back_to_json_when_sse_queue_is_full(_clear_http_globals):
|
||||
"""When the SSE queue is full (>100 pending), the handler returns JSON directly."""
|
||||
import a2a_mcp_server
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
# Pre-register a queue and fill it to capacity
|
||||
conn_id = str(uuid.uuid4())
|
||||
queue: asyncio.Queue = asyncio.Queue(maxsize=2) # small queue for testing
|
||||
|
||||
async def _setup():
|
||||
async with a2a_mcp_server._http_connection_lock:
|
||||
a2a_mcp_server._http_connection_queues[conn_id] = queue
|
||||
queue.put_nowait({"id": 1})
|
||||
queue.put_nowait({"id": 2})
|
||||
|
||||
_sync_run(_setup())
|
||||
assert queue.full()
|
||||
|
||||
app = _build_test_app()
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(
|
||||
"/mcp",
|
||||
headers={"x-mcp-conn-id": conn_id},
|
||||
json={"jsonrpc": "2.0", "id": 99, "method": "initialize", "params": {}},
|
||||
)
|
||||
|
||||
# With a full queue, the handler returns the response as JSON (not 202)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["id"] == 99
|
||||
assert "result" in resp.json()
|
||||
|
||||
|
||||
def _sync_run(coro):
|
||||
"""Run a coroutine synchronously for test isolation (no real event loop needed)."""
|
||||
try:
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
try:
|
||||
return loop.run_until_complete(coro)
|
||||
finally:
|
||||
loop.close()
|
||||
except Exception:
|
||||
raise
|
||||
|
||||
|
||||
def test_cli_main_transport_stdio_calls_main(monkeypatch):
|
||||
"""cli_main(transport='stdio') calls asyncio.run(main) without HTTP."""
|
||||
import a2a_mcp_server
|
||||
|
||||
run_calls: list = []
|
||||
|
||||
async def fake_main():
|
||||
run_calls.append("called")
|
||||
|
||||
monkeypatch.setattr(a2a_mcp_server, "main", fake_main)
|
||||
monkeypatch.setattr(a2a_mcp_server.asyncio, "run", _sync_run)
|
||||
monkeypatch.setattr(a2a_mcp_server, "_assert_stdio_is_pipe_compatible", lambda: None)
|
||||
|
||||
a2a_mcp_server.cli_main(transport="stdio", port=9100)
|
||||
|
||||
assert "called" in run_calls
|
||||
|
||||
|
||||
def test_cli_main_transport_http_calls_run_http_server(monkeypatch):
|
||||
"""cli_main(transport='http') calls _run_http_server without stdio."""
|
||||
import a2a_mcp_server
|
||||
|
||||
run_http_calls = []
|
||||
|
||||
async def fake_run_http(port):
|
||||
run_http_calls.append(port)
|
||||
|
||||
# asyncio.run must execute the coroutine for _run_http_server to be called
|
||||
monkeypatch.setattr(a2a_mcp_server.asyncio, "run", _sync_run)
|
||||
monkeypatch.setattr(a2a_mcp_server, "_run_http_server", fake_run_http)
|
||||
# stdio path must not be entered
|
||||
monkeypatch.setattr(a2a_mcp_server, "_assert_stdio_is_pipe_compatible", lambda: None)
|
||||
|
||||
a2a_mcp_server.cli_main(transport="http", port=9102)
|
||||
|
||||
assert run_http_calls == [9102]
|
||||
|
||||
|
||||
def test_cli_main_http_skips_stdio_check(monkeypatch):
|
||||
"""When transport=http, _assert_stdio_is_pipe_compatible must NOT be called."""
|
||||
import a2a_mcp_server
|
||||
|
||||
called = []
|
||||
|
||||
def fake_assert():
|
||||
called.append("assert_called")
|
||||
|
||||
# Patch on the module object directly
|
||||
monkeypatch.setattr(a2a_mcp_server, "_assert_stdio_is_pipe_compatible", fake_assert)
|
||||
monkeypatch.setattr(a2a_mcp_server.asyncio, "run", lambda fn: None)
|
||||
|
||||
a2a_mcp_server.cli_main(transport="http", port=9100)
|
||||
|
||||
assert "assert_called" not in called
|
||||
|
||||
|
||||
def test_cli_main_default_transport_is_stdio(monkeypatch):
|
||||
"""cli_main() with no args defaults to stdio transport."""
|
||||
import a2a_mcp_server
|
||||
|
||||
called_as: list = []
|
||||
|
||||
async def fake_main():
|
||||
called_as.append("called")
|
||||
|
||||
monkeypatch.setattr(a2a_mcp_server, "main", fake_main)
|
||||
monkeypatch.setattr(a2a_mcp_server.asyncio, "run", _sync_run)
|
||||
monkeypatch.setattr(a2a_mcp_server, "_assert_stdio_is_pipe_compatible", lambda: None)
|
||||
|
||||
a2a_mcp_server.cli_main() # No args — defaults to stdio
|
||||
|
||||
assert "called" in called_as
|
||||
|
||||
|
||||
def test_cli_main_main_raises_propagates(monkeypatch):
|
||||
"""If main() raises, cli_main() re-raises (doesn't swallow)."""
|
||||
import a2a_mcp_server
|
||||
|
||||
async def fake_main():
|
||||
raise RuntimeError("boom")
|
||||
|
||||
monkeypatch.setattr(a2a_mcp_server, "main", fake_main)
|
||||
monkeypatch.setattr(a2a_mcp_server.asyncio, "run", _sync_run)
|
||||
monkeypatch.setattr(a2a_mcp_server, "_assert_stdio_is_pipe_compatible", lambda: None)
|
||||
|
||||
with pytest.raises(RuntimeError, match="boom"):
|
||||
a2a_mcp_server.cli_main(transport="stdio")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# uvicorn/starlette lazy-import
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_run_http_server_is_coroutine_function():
|
||||
"""_run_http_server is a coroutine function accepting a port argument."""
|
||||
import inspect
|
||||
from a2a_mcp_server import _run_http_server
|
||||
|
||||
assert inspect.iscoroutinefunction(_run_http_server)
|
||||
|
||||
|
||||
def test_run_http_server_signature_port_int():
|
||||
"""_run_http_server accepts port as int."""
|
||||
import inspect
|
||||
from a2a_mcp_server import _run_http_server
|
||||
|
||||
sig = inspect.signature(_run_http_server)
|
||||
assert "port" in sig.parameters
|
||||
assert sig.parameters["port"].annotation == int
|
||||
@@ -1,107 +0,0 @@
|
||||
"""Test coverage for builtin_tools.security._redact_secrets().
|
||||
|
||||
Issue #834 (C2): commit_memory must not persist API keys verbatim.
|
||||
|
||||
Pre-commit hook blocks bare secret-like strings (ghp_, sk-ant-, etc.) to prevent
|
||||
accidental commits of real credentials. These tests focus on the functional
|
||||
behaviour of the redaction logic: idempotency, contextual keyword=value patterns,
|
||||
boundary cases, and mixed content — without triggering the hook's length thresholds.
|
||||
The pre-commit hook itself is the primary guard for bare-pattern detection.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from builtin_tools.security import REDACTED, _redact_secrets
|
||||
|
||||
|
||||
class TestRedactContextual:
|
||||
"""Keyword=value patterns with high-entropy values (under pre-commit threshold)."""
|
||||
|
||||
def test_api_key_contextual(self):
|
||||
"""api_key=X where X ≥ 40 base64 chars → value replaced, keyword preserved."""
|
||||
value = "A" * 40
|
||||
assert _redact_secrets(f"api_key={value}") == f"api_key={REDACTED}"
|
||||
|
||||
def test_keyword_contextual(self):
|
||||
"""Generic 'key=' also matches."""
|
||||
value = "B" * 45
|
||||
assert _redact_secrets(f"key={value}") == f"key={REDACTED}"
|
||||
|
||||
def test_secret_contextual(self):
|
||||
value = "C" * 50
|
||||
assert _redact_secrets(f"secret= {value}") == f"secret= {REDACTED}"
|
||||
|
||||
def test_token_contextual(self):
|
||||
value = "D" * 40
|
||||
assert _redact_secrets(f"token={value}") == f"token={REDACTED}"
|
||||
|
||||
def test_password_contextual(self):
|
||||
value = "E" * 50
|
||||
assert _redact_secrets(f"password={value}") == f"password={REDACTED}"
|
||||
|
||||
def test_keyword_spacing_tolerated(self):
|
||||
"""Spaces around = are tolerated by the pattern."""
|
||||
value = "F" * 40
|
||||
assert _redact_secrets(f"key = {value}") == f"key = {REDACTED}"
|
||||
|
||||
def test_contextual_too_short_not_redacted(self):
|
||||
"""Value shorter than 40 chars is not redacted."""
|
||||
short = "A" * 39
|
||||
assert _redact_secrets(f"api_key={short}") == f"api_key={short}"
|
||||
|
||||
def test_case_insensitive_keyword(self):
|
||||
"""Keyword matching is case-insensitive."""
|
||||
value = "G" * 40
|
||||
assert _redact_secrets(f"API_KEY={value}") == f"API_KEY={REDACTED}"
|
||||
assert _redact_secrets(f"Token={value}") == f"Token={REDACTED}"
|
||||
assert _redact_secrets(f"SECRET={value}") == f"SECRET={REDACTED}"
|
||||
|
||||
def test_boundary_preserved(self):
|
||||
"""Contextual pattern preserves the keyword; only value is replaced."""
|
||||
value = "H" * 40
|
||||
result = _redact_secrets(f"api_key={value}")
|
||||
assert result.startswith("api_key=")
|
||||
assert result.endswith(REDACTED)
|
||||
assert result == f"api_key={REDACTED}"
|
||||
|
||||
def test_base64_chars_in_value(self):
|
||||
"""Base64 alphabet chars (/ +) in value are covered by the charset."""
|
||||
# 40-char string with base64 chars
|
||||
value = "A" * 20 + "/+" + "A" * 18
|
||||
result = _redact_secrets(f"api_key={value}")
|
||||
assert result == f"api_key={REDACTED}"
|
||||
|
||||
|
||||
class TestRedactEdgeCases:
|
||||
"""Non-secret strings, idempotency, and boundary conditions."""
|
||||
|
||||
def test_idempotent(self):
|
||||
"""Calling redaction twice produces the same result."""
|
||||
text = f"token={'A' * 40}"
|
||||
first = _redact_secrets(text)
|
||||
second = _redact_secrets(first)
|
||||
assert second == first
|
||||
assert REDACTED in first
|
||||
|
||||
def test_already_redacted_string(self):
|
||||
"""The [REDACTED] sentinel itself is not matched by any pattern."""
|
||||
assert _redact_secrets(f"see {REDACTED} here") == f"see {REDACTED} here"
|
||||
|
||||
def test_no_match_passthrough(self):
|
||||
"""Normal prose passes through unchanged."""
|
||||
assert _redact_secrets("The answer is 42.") == "The answer is 42."
|
||||
assert _redact_secrets("Hello, world!") == "Hello, world!"
|
||||
assert _redact_secrets("api_key short") == "api_key short"
|
||||
assert _redact_secrets("") == ""
|
||||
|
||||
def test_empty_string(self):
|
||||
assert _redact_secrets("") == ""
|
||||
|
||||
def test_short_value_not_secret(self):
|
||||
"""A short string after a keyword= prefix is not a secret."""
|
||||
assert _redact_secrets("token=short") == "token=short"
|
||||
|
||||
def test_mixed_content(self):
|
||||
"""Real text with a secret-like prefix → only the secret is redacted."""
|
||||
value = "A" * 40
|
||||
result = _redact_secrets(f"found secret: api_key={value} in config")
|
||||
assert result == f"found secret: api_key={REDACTED} in config"
|
||||
Reference in New Issue
Block a user