AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
ci(platform): overlap full-stack builds and harden E2E validation (#14281)
Nicholas Tindled46e93bacb80
diff --git a/.github/scripts/test_e2e_seed_cache_contract.py b/.github/scripts/test_e2e_seed_cache_contract.pynew file mode 100644index 0000000000..3f2da4b49c--- /dev/null+++ b/.github/scripts/test_e2e_seed_cache_contract.py@@ -0,0 +1,92 @@+import fnmatch+import re+import unittest+from pathlib import Path+++class E2ESeedCacheContractTests(unittest.TestCase):+ def test_fresh_and_cached_seed_credentials_are_verified_before_tests(self):+ workflow = (+ Path(__file__).resolve().parents[1] / "workflows/platform-fullstack-ci.yml"+ ).read_text(encoding="utf-8")+ name = "Set up tests - Verify seeded credentials with fresh encryption key"+ verification = workflow.split(f"- name: {name}\n", 1)[1].split(+ "\n - name:", 1+ )[0]+ self.assertIn("--refresh-credentials-only", verification)+ self.assertNotIn("if:", verification)+ self.assertNotIn("continue-on-error", verification)+ self.assertLess(+ workflow.index("- name: Set up tests - Create E2E test data"),+ workflow.index(f"- name: {name}"),+ )+ self.assertLess(+ workflow.index(f"- name: {name}"),+ workflow.index("- name: Run Playwright E2E suite"),+ )++ def test_seed_cache_key_uses_pristine_checkout(self):+ workflow = (+ Path(__file__).resolve().parents[1] / "workflows/platform-fullstack-ci.yml"+ ).read_text(encoding="utf-8")+ e2e_job = workflow.split("\n e2e_test:\n", 1)[1]+ steps = re.findall(r"^ - name: (.+)$", e2e_job, re.MULTILINE)+ self.assertEqual(+ steps[:2],+ ["Checkout repository", "Set up tests - Cache E2E test data"],+ "seed cache key must be evaluated before generated env/Compose files exist",+ )++ def test_seed_cache_covers_transitive_inputs(self):+ workflow = (+ Path(__file__).resolve().parents[1] / "workflows/platform-fullstack-ci.yml"+ ).read_text(encoding="utf-8")+ key = next(+ line for line in workflow.splitlines() if "key: e2e-test-data-" in line+ )+ patterns = re.findall(r"'([^']+)'", key)+ for path in (+ "autogpt_platform/backend/test/e2e_test_data.py",+ "autogpt_platform/backend/backend/data/graph.py",+ "autogpt_platform/backend/backend/blocks/calculator.py",+ "autogpt_platform/backend/agents/calculator-agent.json",+ "autogpt_platform/backend/schema.prisma",+ "autogpt_platform/backend/poetry.lock",+ "autogpt_platform/autogpt_libs/autogpt_libs/auth/models.py",+ "autogpt_platform/docker-compose.yml",+ "autogpt_platform/.env.default",+ ".github/workflows/platform-fullstack-ci.yml",+ ):+ with self.subTest(path=path):+ self.assertTrue(+ any(fnmatch.fnmatchcase(path, pattern) for pattern in patterns),+ f"seed cache key does not cover {path}",+ )+++class E2ECoverageContractTests(unittest.TestCase):+ def test_test_floor_includes_shared_file_security_suite(self):+ workflow = (+ Path(__file__).resolve().parents[1] / "workflows/platform-fullstack-ci.yml"+ ).read_text(encoding="utf-8")+ self.assertIn("--min-tests 28", workflow)++ def test_codecov_requires_validated_coverage(self):+ workflow = (+ Path(__file__).resolve().parents[1] / "workflows/platform-fullstack-ci.yml"+ ).read_text(encoding="utf-8")+ validator = workflow.split("- name: Validate coverage report\n", 1)[1].split(+ "\n - name:", 1+ )[0]+ upload = workflow.split("- name: Upload E2E coverage to Codecov\n", 1)[1]+ self.assertIn("id: validate-e2e-coverage", validator)+ self.assertIn("if: ${{ always() }}", validator)+ self.assertNotIn("continue-on-error", validator)+ self.assertIn(+ "if: ${{ !cancelled() && steps.validate-e2e-coverage.outcome == 'success' }}",+ upload,+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/.github/scripts/test_validate_playwright_json.py b/.github/scripts/test_validate_playwright_json.pynew file mode 100644index 0000000000..a63f3e209c--- /dev/null+++ b/.github/scripts/test_validate_playwright_json.py@@ -0,0 +1,167 @@+import copy+import json+import tempfile+import unittest+from pathlib import Path++from validate_playwright_json import main, validate_report+++def valid_report() -> dict[str, object]:+ return {+ "config": {"projects": [{"name": "chromium", "retries": 0}]},+ "errors": [],+ "stats": {+ "expected": 1,+ "skipped": 0,+ "unexpected": 0,+ "flaky": 0,+ },+ "suites": [+ {+ "specs": [+ {+ "tests": [+ {+ "status": "expected",+ "expectedStatus": "passed",+ "results": [+ {+ "retry": 0,+ "status": "passed",+ "errors": [],+ }+ ],+ }+ ]+ }+ ],+ "suites": [],+ }+ ],+ }+++class ValidatePlaywrightJSONTests(unittest.TestCase):+ def test_accepts_clean_single_attempt_report(self):+ self.assertEqual(validate_report(valid_report()), 1)++ def test_rejects_configured_retries(self):+ report = valid_report()+ report["config"]["projects"][0]["retries"] = 2++ with self.assertRaisesRegex(ValueError, "retries must be 0"):+ validate_report(report)++ def test_rejects_flaky_test_that_eventually_passed(self):+ report = valid_report()+ report["stats"]["expected"] = 0+ report["stats"]["flaky"] = 1+ test = report["suites"][0]["specs"][0]["tests"][0]+ test["status"] = "flaky"+ test["results"].insert(+ 0, {"retry": 0, "status": "failed", "errors": [{"message": "boom"}]}+ )+ test["results"][1]["retry"] = 1++ with self.assertRaisesRegex(ValueError, "stats.flaky must be 0"):+ validate_report(report)++ def test_rejects_skipped_test(self):+ report = valid_report()+ report["stats"]["expected"] = 0+ report["stats"]["skipped"] = 1++ with self.assertRaisesRegex(ValueError, "stats.skipped must be 0"):+ validate_report(report)++ def test_rejects_multiple_attempts_even_when_stats_claim_clean(self):+ report = valid_report()+ test = report["suites"][0]["specs"][0]["tests"][0]+ test["results"].append(copy.deepcopy(test["results"][0]))++ with self.assertRaisesRegex(ValueError, "exactly one attempt"):+ validate_report(report)++ def test_rejects_invalid_tests_even_when_aggregate_stats_are_clean(self):+ for field, value, message in (+ ("status", "flaky", ".status must be expected"),+ ("expectedStatus", "failed", ".expectedStatus must be passed"),+ ):+ with self.subTest(field=field):+ report = valid_report()+ report["suites"][0]["specs"][0]["tests"][0][field] = value+ with self.assertRaisesRegex(ValueError, message):+ validate_report(report)++ def test_rejects_invalid_results_even_when_aggregate_stats_are_clean(self):+ for field, value, message in (+ ("status", "failed", ".status must be passed"),+ ("errors", [{"message": "boom"}], "contains 1 errors"),+ ("retry", 1, ".retry must be 0"),+ ):+ with self.subTest(field=field):+ report = valid_report()+ report["suites"][0]["specs"][0]["tests"][0]["results"][0][field] = value+ with self.assertRaisesRegex(ValueError, message):+ validate_report(report)++ def test_rejects_zero_test_report(self):+ report = valid_report()+ report["stats"]["expected"] = 0+ report["suites"] = []++ with self.assertRaisesRegex(ValueError, "zero expected tests"):+ validate_report(report)++ def test_rejects_report_below_required_inventory(self):+ with self.assertRaisesRegex(ValueError, "below required minimum 2"):+ validate_report(valid_report(), min_tests=2)++ def test_rejects_boolean_retry_value(self):+ report = valid_report()+ report["suites"][0]["specs"][0]["tests"][0]["results"][0]["retry"] = False++ with self.assertRaisesRegex(ValueError, "non-negative integer"):+ validate_report(report)++ def test_synthesizes_machine_readable_error_for_missing_report(self):+ with tempfile.TemporaryDirectory() as directory:+ report_path = Path(directory) / "results.json"++ self.assertEqual(+ main(["--synthesize-invalid", str(report_path)]),+ 1,+ )+ synthesized = json.loads(report_path.read_text(encoding="utf-8"))+ self.assertEqual(synthesized["stats"]["unexpected"], 1)+ self.assertEqual(len(synthesized["errors"]), 1)++ def test_preserves_semantically_failed_report(self):+ with tempfile.TemporaryDirectory() as directory:+ report_path = Path(directory) / "results.json"+ report = valid_report()+ report["stats"]["flaky"] = 1+ report_path.write_text(json.dumps(report), encoding="utf-8")+ original = report_path.read_text(encoding="utf-8")++ self.assertEqual(+ main(["--synthesize-invalid", str(report_path)]),+ 1,+ )+ self.assertEqual(report_path.read_text(encoding="utf-8"), original)++ def test_missing_tests_fails_cleanly_and_preserves_original_report(self):+ with tempfile.TemporaryDirectory() as directory:+ report_path = Path(directory) / "results.json"+ report = valid_report()+ del report["suites"][0]["specs"][0]["tests"]+ original = json.dumps(report)+ report_path.write_text(original, encoding="utf-8")++ self.assertEqual(main(["--synthesize-invalid", str(report_path)]), 1)+ self.assertEqual(report_path.read_text(encoding="utf-8"), original)+++if __name__ == "__main__":+ unittest.main()diff --git a/.github/scripts/validate_playwright_json.py b/.github/scripts/validate_playwright_json.pynew file mode 100644index 0000000000..95e93fdde5--- /dev/null+++ b/.github/scripts/validate_playwright_json.py@@ -0,0 +1,196 @@+#!/usr/bin/env python3++import argparse+import json+from pathlib import Path+from typing import Iterator+++def _require_mapping(value: object, name: str) -> dict[str, object]:+ if not isinstance(value, dict):+ raise ValueError(f"{name} must be an object")+ return value+++def _require_list(value: object, name: str) -> list[object]:+ if not isinstance(value, list):+ raise ValueError(f"{name} must be an array")+ return value+++def _require_count(value: object, name: str) -> int:+ if type(value) is not int or value < 0:+ raise ValueError(f"{name} must be a non-negative integer")+ return value+++def _iter_tests(+ suites: list[object], location: str = "suites"+) -> Iterator[dict[str, object]]:+ for suite_index, raw_suite in enumerate(suites):+ suite_name = f"{location}[{suite_index}]"+ suite = _require_mapping(raw_suite, suite_name)+ for spec_index, raw_spec in enumerate(+ _require_list(suite.get("specs", []), f"{suite_name}.specs")+ ):+ spec_name = f"{suite_name}.specs[{spec_index}]"+ spec = _require_mapping(raw_spec, spec_name)+ for test_index, raw_test in enumerate(+ _require_list(spec.get("tests"), f"{spec_name}.tests")+ ):+ yield _require_mapping(raw_test, f"{spec_name}.tests[{test_index}]")+ yield from _iter_tests(+ _require_list(suite.get("suites", []), f"{suite_name}.suites"),+ f"{suite_name}.suites",+ )+++def validate_report(report: object, min_tests: int = 1) -> int:+ root = _require_mapping(report, "report")+ errors = _require_list(root.get("errors"), "errors")+ if errors:+ raise ValueError(f"report contains {len(errors)} top-level errors")++ config = _require_mapping(root.get("config"), "config")+ projects = _require_list(config.get("projects"), "config.projects")+ if not projects:+ raise ValueError("config.projects must contain at least one project")+ for index, raw_project in enumerate(projects):+ project = _require_mapping(raw_project, f"config.projects[{index}]")+ retries = _require_count(+ project.get("retries"), f"config.projects[{index}].retries"+ )+ if retries != 0:+ raise ValueError(+ f"config.projects[{index}].retries must be 0, got {retries}"+ )++ stats = _require_mapping(root.get("stats"), "stats")+ counts = {+ key: _require_count(stats.get(key), f"stats.{key}")+ for key in ("expected", "skipped", "unexpected", "flaky")+ }+ for key in ("skipped", "unexpected", "flaky"):+ if counts[key] != 0:+ raise ValueError(f"stats.{key} must be 0, got {counts[key]}")+ if counts["expected"] == 0:+ raise ValueError("report contains zero expected tests")++ tests = list(_iter_tests(_require_list(root.get("suites"), "suites")))+ if len(tests) != counts["expected"]:+ raise ValueError(+ f"discovered {len(tests)} tests but stats.expected is {counts['expected']}"+ )+ if len(tests) < min_tests:+ raise ValueError(+ f"report contains {len(tests)} tests, below required minimum {min_tests}"+ )++ for index, test in enumerate(tests):+ test_name = f"test[{index}]"+ if test.get("status") != "expected":+ raise ValueError(+ f"{test_name}.status must be expected, got {test.get('status')!r}"+ )+ if test.get("expectedStatus") != "passed":+ raise ValueError(+ f"{test_name}.expectedStatus must be passed, got "+ f"{test.get('expectedStatus')!r}"+ )+ results = _require_list(test.get("results"), f"{test_name}.results")+ if len(results) != 1:+ raise ValueError(+ f"{test_name}.results must contain exactly one attempt, got {len(results)}"+ )+ result = _require_mapping(results[0], f"{test_name}.results[0]")+ retry = _require_count(result.get("retry"), f"{test_name}.results[0].retry")+ if retry != 0:+ raise ValueError(f"{test_name}.results[0].retry must be 0, got {retry}")+ if result.get("status") != "passed":+ raise ValueError(+ f"{test_name}.results[0].status must be passed, got "+ f"{result.get('status')!r}"+ )+ result_errors = _require_list(+ result.get("errors"), f"{test_name}.results[0].errors"+ )+ if result_errors:+ raise ValueError(+ f"{test_name}.results[0] contains {len(result_errors)} errors"+ )++ return len(tests)+++def _write_invalid_report(path: Path, error: str) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps(+ {+ "config": {"projects": []},+ "suites": [],+ "errors": [{"message": error}],+ "stats": {+ "startTime": "",+ "duration": 0,+ "expected": 0,+ "skipped": 0,+ "unexpected": 1,+ "flaky": 0,+ },+ },+ indent=2,+ )+ + "\n",+ encoding="utf-8",+ )+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Fail unless a Playwright JSON report is complete and clean."+ )+ parser.add_argument(+ "--synthesize-invalid",+ action="store_true",+ help="replace a missing, empty, or malformed report with a machine-readable error",+ )+ parser.add_argument(+ "--min-tests",+ type=int,+ default=1,+ help="minimum number of discovered passing tests required",+ )+ parser.add_argument("report", type=Path)+ return parser.parse_args(argv)+++def main(argv: list[str] | None = None) -> int:+ args = parse_args(argv)+ if args.min_tests < 1:+ print("--min-tests must be at least 1")+ return 2+ try:+ raw_report = args.report.read_text(encoding="utf-8")+ if not raw_report.strip():+ raise ValueError("report is empty")+ report = json.loads(raw_report)+ except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc:+ problem = f"{args.report}: {exc}"+ if args.synthesize_invalid:+ _write_invalid_report(args.report, problem)+ print(problem)+ return 1++ try:+ test_count = validate_report(report, min_tests=args.min_tests)+ except ValueError as exc:+ print(f"{args.report}: {exc}")+ return 1++ print(f"{args.report}: {test_count} tests passed once without skips or retries")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/workflows/platform-fullstack-ci.yml b/.github/workflows/platform-fullstack-ci.ymlindex 865585dd9a..2539ea4ef3 100644--- a/.github/workflows/platform-fullstack-ci.yml+++ b/.github/workflows/platform-fullstack-ci.yml@@ -5,20 +5,38 @@ on:branches: [master, dev]paths:- ".github/workflows/platform-fullstack-ci.yml"+ - ".github/scripts/validate_playwright_json.py"+ - ".github/scripts/test_validate_playwright_json.py"+ - ".github/scripts/validate_cobertura.py"+ - ".github/scripts/test_validate_cobertura.py"+ - ".github/scripts/test_e2e_seed_cache_contract.py"+ - ".github/scripts/docker-pull-with-retry.sh"- ".github/workflows/scripts/docker-ci-fix-compose-build-cache.py"- ".github/workflows/scripts/get_package_version_from_lockfile.py"- "autogpt_platform/**"pull_request:paths:- ".github/workflows/platform-fullstack-ci.yml"+ - ".github/scripts/validate_playwright_json.py"+ - ".github/scripts/test_validate_playwright_json.py"+ - ".github/scripts/validate_cobertura.py"+ - ".github/scripts/test_validate_cobertura.py"+ - ".github/scripts/test_e2e_seed_cache_contract.py"+ - ".github/scripts/docker-pull-with-retry.sh"- ".github/workflows/scripts/docker-ci-fix-compose-build-cache.py"- ".github/workflows/scripts/get_package_version_from_lockfile.py"- "autogpt_platform/**"merge_group:workflow_dispatch:+ inputs:+ publish_build_cache:+ description: Export this test commit's Docker build cache+ required: false+ default: false+ type: booleanconcurrency:- group: ${{ github.workflow }}-${{ github.event_name == 'merge_group' && format('merge-queue-{0}', github.ref) || github.head_ref && format('pr-{0}', github.event.pull_request.number) || github.sha }}+ group: ${{ github.event_name == 'workflow_dispatch' && format('{0}-dispatch-{1}', github.workflow, github.run_id) || format('{0}-{1}', github.workflow, github.event_name == 'merge_group' && format('merge-queue-{0}', github.ref) || github.head_ref && format('pr-{0}', github.event.pull_request.number) || github.sha) }}cancel-in-progress: ${{ github.event_name == 'pull_request' }}defaults:@@ -30,37 +48,15 @@ permissions:contents: readjobs:- setup:- runs-on: ubuntu-latest-- steps:- - name: Checkout repository- uses: actions/checkout@v6-- - name: Set up pnpm- uses: pnpm/action-setup@v4- with:- package_json_file: autogpt_platform/frontend/package.json-- - name: Set up Node- uses: actions/setup-node@v6- with:- node-version: "24.18.0"- cache: "pnpm"- cache-dependency-path: autogpt_platform/frontend/pnpm-lock.yaml-- - name: Install dependencies to populate cache- run: pnpm install --frozen-lockfile-check-api-types:name: check API typesruns-on: ubuntu-latest- needs: setupsteps:- name: Checkout repositoryuses: actions/checkout@v6with:+ ref: ${{ github.sha }}submodules: recursive# ------------------------ Backend setup ------------------------@@ -87,6 +83,16 @@ jobs:working-directory: autogpt_platform/backendrun: poetry install+ - name: Test full-stack report validators+ working-directory: autogpt_platform/backend+ run: |+ mkdir -p "$RUNNER_TEMP/fullstack-validator-results"+ poetry run pytest \+ ../../.github/scripts/test_validate_playwright_json.py \+ ../../.github/scripts/test_validate_cobertura.py \+ ../../.github/scripts/test_e2e_seed_cache_contract.py \+ --junitxml="$RUNNER_TEMP/fullstack-validator-results/playwright-validator-tests.xml"+- name: Set up Backend - Generate Prisma clientworking-directory: autogpt_platform/backendrun: poetry run prisma generate && poetry run gen-prisma-stub@@ -150,19 +156,47 @@ jobs:run: pnpm typesif: success() || (steps.generate-api-client.outcome == 'success')+ - name: Upload validator test report+ if: ${{ always() }}+ uses: actions/upload-artifact@v7+ with:+ name: fullstack-validator-tests+ path: ${{ runner.temp }}/fullstack-validator-results/playwright-validator-tests.xml+ if-no-files-found: error+e2e_test:name: end-to-end testsruns-on: big-boi+ env:+ BUILDKIT_IMAGE: docker.io/moby/buildkit:v0.32.0@sha256:1f8167fcb0eca5b7126353d35299386945cbb8949cc516c592a49f80cfce4fa2steps:- name: Checkout repositoryuses: actions/checkout@v6with:+ ref: ${{ github.sha }}submodules: recursive+ - name: Set up tests - Cache E2E test data+ id: e2e-data-cache+ uses: actions/cache@v5+ with:+ path: /tmp/e2e_test_data.sql+ # Hash checkout inputs before fresh secrets and resolved Compose exist.+ key: e2e-test-data-v3-${{ hashFiles('autogpt_platform/backend/**', 'autogpt_platform/autogpt_libs/**', 'autogpt_platform/docker-compose*.yml', 'autogpt_platform/.env.default', '.github/workflows/platform-fullstack-ci.yml') }}++ - name: Set up Platform - Pull BuildKit image+ id: buildkit-image+ working-directory: /tmp+ timeout-minutes: 5+ background: true+ run: |+ if docker image inspect "$BUILDKIT_IMAGE" >/dev/null 2>&1; then+ exit 0+ fi+ bash "$GITHUB_WORKSPACE/.github/scripts/docker-pull-with-retry.sh" "$BUILDKIT_IMAGE"+- name: Set up Platform - Create .env files with generated secrets- # Same bootstrap a contributor runs: .env.default ships its secrets- # blank, and this fills them with values generated for this run.working-directory: autogpt_platformrun: make init-env@@ -175,17 +209,16 @@ jobs:# Used by E2E test data script to generate embeddings for approved store agentsOPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}- - name: Set up Platform - Set up Docker Buildx- uses: docker/setup-buildx-action@v3- with:- driver: docker-container- driver-opts: network=host-- name: Set up Platform - Expose GHA cache to docker buildx CLIuses: crazy-max/ghaction-github-runtime@v4- - name: Set up Platform - Build Docker images (with cache)+ - name: Set up Platform - Prepare Docker buildworking-directory: autogpt_platform+ env:+ NEXT_PUBLIC_PW_TEST: true+ NEXT_PUBLIC_SOURCEMAPS: true+ GIT_REF: ${{ github.ref }}+ PUBLISH_BUILD_CACHE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/dev') || (github.event_name == 'workflow_dispatch' && inputs.publish_build_cache) }}run: |pip install pyyaml@@ -200,34 +233,77 @@ jobs:sed -i '/NEXT_PUBLIC_PW_TEST/a\ NEXT_PUBLIC_SOURCEMAPS: "true"' docker-compose.resolved.ymlfi- # Add cache configuration to the resolved compose file+ cache_to=""+ if [[ "$PUBLISH_BUILD_CACHE" == "true" ]]; then+ cache_to="type=gha,mode=max"+ fi+python ../.github/workflows/scripts/docker-ci-fix-compose-build-cache.py \--source docker-compose.resolved.yml \--cache-from "type=gha" \- --cache-to "type=gha,mode=max" \--backend-hash "${{ hashFiles('autogpt_platform/backend/Dockerfile', 'autogpt_platform/backend/poetry.lock', 'autogpt_platform/backend/backend/**') }}" \--frontend-hash "${{ hashFiles('autogpt_platform/frontend/Dockerfile', 'autogpt_platform/frontend/pnpm-lock.yaml', 'autogpt_platform/frontend/src/**') }}-sourcemaps" \- --git-ref "${{ github.ref }}"+ --git-ref "$GIT_REF" \+ --cache-to "$cache_to"++ - name: Set up Platform - Wait for BuildKit image+ wait: [buildkit-image]- # Build with bake using the resolved compose file (now includes cache config)+ - name: Set up Platform - Set up Docker Buildx+ uses: docker/setup-buildx-action@v3+ with:+ driver: docker-container+ driver-opts: |+ image=${{ env.BUILDKIT_IMAGE }}+ network=host++ - name: Set up Platform - Build Docker images+ id: platform-build+ working-directory: autogpt_platform+ background: true+ run: |docker buildx bake --allow=fs.read=.. -f docker-compose.resolved.yml --loadenv:NEXT_PUBLIC_PW_TEST: trueNEXT_PUBLIC_SOURCEMAPS: true- - name: Set up tests - Cache E2E test data- id: e2e-data-cache- uses: actions/cache@v5- with:- path: /tmp/e2e_test_data.sql- key: e2e-test-data-${{ hashFiles('autogpt_platform/backend/test/e2e_test_data.py', 'autogpt_platform/backend/backend/data/user.py', 'autogpt_platform/backend/migrations/**', '.github/workflows/platform-fullstack-ci.yml') }}-- name: Set up Platform - Start database+ id: database+ background: truerun: |docker compose -f ../docker-compose.resolved.yml up -d db --no-buildecho "Waiting for database to be ready..."timeout 60 sh -c 'until docker compose -f ../docker-compose.resolved.yml exec -T db pg_isready -U postgres 2>/dev/null; do sleep 2; done'+ - name: Set up tests - Set up pnpm+ uses: pnpm/action-setup@v4+ with:+ package_json_file: autogpt_platform/frontend/package.json++ - name: Set up tests - Set up Node+ uses: actions/setup-node@v6+ with:+ node-version: "24.18.0"+ cache: "pnpm"+ cache-dependency-path: autogpt_platform/frontend/pnpm-lock.yaml++ - name: Set up tests - Cache Playwright browsers+ uses: actions/cache@v5+ with:+ path: ~/.cache/ms-playwright+ key: playwright-${{ runner.os }}-${{ hashFiles('autogpt_platform/frontend/pnpm-lock.yaml') }}+ restore-keys: |+ playwright-${{ runner.os }}-++ - name: Set up tests - Install dependencies+ run: pnpm install --frozen-lockfile --prefer-offline++ - name: Set up tests - Install browser 'chromium'+ run: pnpm playwright install --with-deps chromium++ - name: Wait for image build and database+ wait: [platform-build, database]+- name: Set up Platform - Run migrationsrun: |echo "Running migrations..."@@ -244,10 +320,10 @@ jobs:echo "SET session_replication_role = 'replica';"cat /tmp/e2e_test_data.sqlecho "SET session_replication_role = 'origin';"- } | docker compose -f ../docker-compose.resolved.yml exec -T db psql -U postgres -d postgres -b+ } | docker compose -f ../docker-compose.resolved.yml exec -T db psql -X -v ON_ERROR_STOP=1 -U postgres -d postgres -b# Refresh materialized views after restoredocker compose -f ../docker-compose.resolved.yml exec -T db \- psql -U postgres -d postgres -b -c "SET search_path TO platform; SELECT refresh_store_materialized_views();" || true+ psql -X -v ON_ERROR_STOP=1 -U postgres -d postgres -b -c "SET search_path TO platform; SELECT refresh_store_materialized_views();"echo "✅ E2E test data restored from cache"@@ -260,6 +336,12 @@ jobs:docker compose -f ../docker-compose.resolved.yml logs --tail=100 rest_serverexit 1}+ echo "Waiting for scheduler_server to be ready..."+ timeout 180 sh -c 'until curl -fsS http://localhost:8003/health_check >/dev/null; do sleep 2; done' || {+ echo "scheduler_server did not become healthy in 180s"+ docker compose -f ../docker-compose.resolved.yml logs --tail=100 scheduler_server+ exit 1+ }env:NEXT_PUBLIC_PW_TEST: true@@ -287,43 +369,41 @@ jobs:echo "✅ Database dump created for caching ($(wc -l < /tmp/e2e_test_data.sql) lines)"- - name: Set up tests - Set up pnpm- uses: pnpm/action-setup@v4- with:- package_json_file: autogpt_platform/frontend/package.json-- - name: Set up tests - Set up Node- uses: actions/setup-node@v6- with:- node-version: "24.18.0"- cache: "pnpm"- cache-dependency-path: autogpt_platform/frontend/pnpm-lock.yaml-- - name: Set up tests - Cache Playwright browsers- uses: actions/cache@v5- with:- path: ~/.cache/ms-playwright- key: playwright-${{ runner.os }}-${{ hashFiles('autogpt_platform/frontend/pnpm-lock.yaml') }}- restore-keys: |- playwright-${{ runner.os }}-+ - name: Set up tests - Verify seeded credentials with fresh encryption key+ run: |+ docker cp ../backend/test/e2e_test_data.py $(docker compose -f ../docker-compose.resolved.yml ps -q rest_server):/tmp/e2e_test_data.py+ docker compose -f ../docker-compose.resolved.yml exec -T rest_server \+ sh -c "cd /app/autogpt_platform && python /tmp/e2e_test_data.py --refresh-credentials-only"- name: Copy source maps from Docker for E2E coveragerun: |FRONTEND_CONTAINER=$(docker compose -f ../docker-compose.resolved.yml ps -q frontend)docker cp "$FRONTEND_CONTAINER":/app/.next/static .next-static-coverage- - name: Set up tests - Install dependencies- run: pnpm install --frozen-lockfile-- - name: Set up tests - Install browser 'chromium'- run: pnpm playwright install --with-deps chromium-- name: Run Playwright E2E suite- run: pnpm test:e2e:no-build- continue-on-error: false+ run: pnpm exec playwright test --retries=0 --trace=retain-on-failure+ env:+ PLAYWRIGHT_JSON_OUTPUT_FILE: test-results/results.json+ PLAYWRIGHT_RETRIES: "0"++ - name: Validate Playwright JSON report+ if: ${{ always() }}+ # Pinned inventory: 28 tests in 9 files; raise when adding E2E tests.+ run: >-+ python ../../.github/scripts/validate_playwright_json.py+ --synthesize-invalid+ --min-tests 28+ test-results/results.json++ - name: Validate coverage report+ id: validate-e2e-coverage+ if: ${{ always() }}+ run: >-+ python ../../.github/scripts/validate_cobertura.py+ coverage/e2e/cobertura-coverage.xml- name: Upload E2E coverage to Codecov- if: ${{ !cancelled() }}+ if: ${{ !cancelled() && steps.validate-e2e-coverage.outcome == 'success' }}uses: codecov/codecov-action@v5with:token: ${{ secrets.CODECOV_TOKEN }}@@ -341,12 +421,14 @@ jobs:retention-days: 3- name: Upload Playwright test results- if: always()+ if: ${{ always() }}uses: actions/upload-artifact@v7with:name: playwright-test-results- path: autogpt_platform/frontend/test-results- if-no-files-found: ignore+ path: |+ autogpt_platform/frontend/test-results+ autogpt_platform/frontend/coverage/e2e/cobertura-coverage.xml+ if-no-files-found: errorretention-days: 3- name: Print Final Docker Compose logsdiff --git a/.github/workflows/scripts/docker-ci-fix-compose-build-cache.py b/.github/workflows/scripts/docker-ci-fix-compose-build-cache.pyindex 33693fc739..4641beb57c 100644--- a/.github/workflows/scripts/docker-ci-fix-compose-build-cache.py+++ b/.github/workflows/scripts/docker-ci-fix-compose-build-cache.py@@ -30,7 +30,7 @@ def main():parser.add_argument("--cache-to",default="type=gha,mode=max",- help="Cache destination configuration",+ help="Cache destination configuration; pass an empty value to disable export",)for component in CACHE_BUILDS_FOR_COMPONENTS:parser.add_argument(@@ -149,7 +149,7 @@ def main():master_scope = f"platform-{component}-{target}-{DEFAULT_BRANCH}"cache_from_list.append(f"{args.cache_from},scope={master_scope}")- if "type=gha" in args.cache_to:+ if args.cache_to and "type=gha" in args.cache_to:# Write to both hash-based and branch-based scopesif component_hash:hash_scope = f"platform-{component}-{target}-{component_hash}"@@ -162,11 +162,14 @@ def main():# Ensure we have at least one cache source/targetif not cache_from_list:cache_from_list.append(args.cache_from)- if not cache_to_list:+ if args.cache_to and not cache_to_list:cache_to_list.append(args.cache_to)build_config["cache_from"] = cache_from_list- build_config["cache_to"] = cache_to_list+ if cache_to_list:+ build_config["cache_to"] = cache_to_list+ else:+ build_config.pop("cache_to", None)modified_services.append(service_name)# Write back to the same filediff --git a/autogpt_platform/backend/test/e2e_test_data.py b/autogpt_platform/backend/test/e2e_test_data.pyindex 0e830f7e5c..0210bc5d11 100644--- a/autogpt_platform/backend/test/e2e_test_data.py+++ b/autogpt_platform/backend/test/e2e_test_data.py@@ -12,6 +12,7 @@ Image/Video URL Domains Used:- Videos: youtube.com (for store listing video URLs)"""+import argparseimport asyncioimport jsonimport os@@ -107,6 +108,45 @@ SEEDED_TEST_EMAILS = []+def make_seed_credential(credential_id: str) -> APIKeyCredentials:+ return APIKeyCredentials(+ id=credential_id,+ provider="github",+ api_key=SecretStr("ghp_kitchensink_seed"),+ title="Kitchen-sink GitHub",+ )+++async def refresh_seeded_credentials() -> None:+ users = await prisma.user.find_many(where={"email": {"in": SEEDED_TEST_EMAILS}})+ owner_ids = {user.id for user in users}+ if len(owner_ids) != len(SEEDED_TEST_EMAILS):+ raise ValueError("Seeded credential owners are missing")+ credentials = await prisma.integrationcredential.find_many(+ where={+ "ownerType": prisma_enums.CredentialOwnerType.USER,+ "ownerId": {"in": sorted(owner_ids)},+ "provider": "github",+ "displayName": "Kitchen-sink GitHub",+ }+ )+ if (+ len(credentials) != len(owner_ids)+ or {credential.ownerId for credential in credentials} != owner_ids+ ):+ raise ValueError("Expected one marked credential per seeded user")+ cryptor = JSONCryptor()+ for credential in credentials:+ payload = make_seed_credential(credential.id).model_dump()+ updated = await prisma.integrationcredential.update(+ where={"id": credential.id},+ data={"encryptedPayload": cryptor.encrypt(payload)},+ )+ if updated is None or cryptor.decrypt(updated.encryptedPayload) != payload:+ raise ValueError("Seeded credential failed encryption verification")+ print(f"Verified {len(credentials)} seeded credentials with the current run key")++def get_video_url():"""Generate a consistent video URL using YouTube."""video_ids = [@@ -1171,12 +1211,7 @@ class TestDataCreator:# decrypt/validate read path (get_user_credentials) accepts it.# (A raw/plaintext payload is silently rejected and never shows.)cred_id = str(uuid.uuid4())- gh_cred = APIKeyCredentials(- id=cred_id,- provider="github",- api_key=SecretStr("ghp_kitchensink_seed"),- title="Kitchen-sink GitHub",- )+ gh_cred = make_seed_credential(cred_id)await _try("credential",prisma.integrationcredential.create(@@ -1366,12 +1401,18 @@ def _seconds_left(deadline: float) -> float:async def main():"""Main function to run the test data creation."""+ parser = argparse.ArgumentParser()+ parser.add_argument("--refresh-credentials-only", action="store_true")+ args = parser.parse_args()# Connect to databaseawait prisma.connect()try:- creator = TestDataCreator()- await creator.create_all_test_data()+ if args.refresh_credentials_only:+ await refresh_seeded_credentials()+ else:+ creator = TestDataCreator()+ await creator.create_all_test_data()finally:# Disconnect from databaseawait prisma.disconnect()diff --git a/autogpt_platform/backend/test/test_e2e_seed_credentials.py b/autogpt_platform/backend/test/test_e2e_seed_credentials.pynew file mode 100644index 0000000000..2c2b40b42e--- /dev/null+++ b/autogpt_platform/backend/test/test_e2e_seed_credentials.py@@ -0,0 +1,150 @@+from test import e2e_test_data+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock+from uuid import uuid4++import pytest+from cryptography.fernet import Fernet++from backend.util.encryption import JSONCryptor+++def seeded_credentials(monkeypatch):+ old_cryptor = JSONCryptor(Fernet.generate_key().decode())+ current_cryptor = JSONCryptor(Fernet.generate_key().decode())+ users = [SimpleNamespace(id=str(uuid4())) for _ in e2e_test_data.SEEDED_TEST_EMAILS]+ rows = []+ for user in users:+ credential_id = str(uuid4())+ rows.append(+ SimpleNamespace(+ id=credential_id,+ ownerId=user.id,+ encryptedPayload=old_cryptor.encrypt(+ e2e_test_data.make_seed_credential(credential_id).model_dump()+ ),+ )+ )++ async def update(*, where, data):+ row = next(row for row in rows if row.id == where["id"])+ row.encryptedPayload = data["encryptedPayload"]+ return row++ db = SimpleNamespace(+ user=SimpleNamespace(find_many=AsyncMock(return_value=users)),+ integrationcredential=SimpleNamespace(+ find_many=AsyncMock(return_value=rows), update=AsyncMock(side_effect=update)+ ),+ )+ monkeypatch.setattr(e2e_test_data, "prisma", db)+ monkeypatch.setattr(e2e_test_data, "JSONCryptor", lambda: current_cryptor)+ return db, rows, current_cryptor+++async def test_cached_credentials_remain_readable_with_a_fresh_key(seeded_credentials):+ db, rows, cryptor = seeded_credentials+ assert all(cryptor.decrypt(row.encryptedPayload) == {} for row in rows)+ await e2e_test_data.refresh_seeded_credentials()+ assert db.integrationcredential.update.await_count == len(rows)+ for row in rows:+ assert (+ cryptor.decrypt(row.encryptedPayload)+ == e2e_test_data.make_seed_credential(row.id).model_dump()+ )+ db.user.find_many.assert_awaited_once_with(+ where={"email": {"in": e2e_test_data.SEEDED_TEST_EMAILS}}+ )+ db.integrationcredential.find_many.assert_awaited_once_with(+ where={+ "ownerType": e2e_test_data.prisma_enums.CredentialOwnerType.USER,+ "ownerId": {"in": sorted(row.ownerId for row in rows)},+ "provider": "github",+ "displayName": "Kitchen-sink GitHub",+ }+ )+++async def test_missing_seeded_user_fails_before_updates(seeded_credentials):+ db, _, _ = seeded_credentials+ db.user.find_many.return_value = db.user.find_many.return_value[:-1]+ with pytest.raises(ValueError, match="owners are missing"):+ await e2e_test_data.refresh_seeded_credentials()+ db.integrationcredential.update.assert_not_awaited()+++ "invalid_rows", ["missing", "duplicate_owner", "foreign_owner"]+)+async def test_incomplete_or_wrong_fixture_set_fails_closed(+ seeded_credentials, invalid_rows+):+ db, rows, _ = seeded_credentials+ if invalid_rows == "missing":+ db.integrationcredential.find_many.return_value = rows[:-1]+ elif invalid_rows == "duplicate_owner":+ rows[-1].ownerId = rows[0].ownerId+ else:+ rows[-1].ownerId = str(uuid4())+ with pytest.raises(ValueError, match="one marked credential per seeded user"):+ await e2e_test_data.refresh_seeded_credentials()+ db.integrationcredential.update.assert_not_awaited()+++async def test_database_update_failure_is_not_swallowed(seeded_credentials):+ db, _, _ = seeded_credentials+ db.integrationcredential.update.side_effect = RuntimeError("update failed")+ with pytest.raises(RuntimeError, match="update failed"):+ await e2e_test_data.refresh_seeded_credentials()++[email protected]("returned_row", ["missing", "stale"])+async def test_failed_encryption_verification_is_not_swallowed(+ seeded_credentials, returned_row+):+ db, rows, _ = seeded_credentials+ db.integrationcredential.update.side_effect = None+ db.integrationcredential.update.return_value = (+ None if returned_row == "missing" else rows[0]+ )+ with pytest.raises(ValueError, match="encryption verification"):+ await e2e_test_data.refresh_seeded_credentials()++[email protected]("refresh_only", [False, True])+async def test_command_routes_without_reseeding_cached_data(monkeypatch, refresh_only):+ db = SimpleNamespace(connect=AsyncMock(), disconnect=AsyncMock())+ creator = SimpleNamespace(create_all_test_data=AsyncMock())+ factory = Mock(return_value=creator)+ refresh = AsyncMock()+ monkeypatch.setattr(e2e_test_data, "prisma", db)+ monkeypatch.setattr(e2e_test_data, "TestDataCreator", factory)+ monkeypatch.setattr(e2e_test_data, "refresh_seeded_credentials", refresh)+ args = ["e2e_test_data.py"]+ if refresh_only:+ args.append("--refresh-credentials-only")+ monkeypatch.setattr("sys.argv", args)+ await e2e_test_data.main()+ db.connect.assert_awaited_once()+ db.disconnect.assert_awaited_once()+ if refresh_only:+ refresh.assert_awaited_once()+ factory.assert_not_called()+ else:+ creator.create_all_test_data.assert_awaited_once()+ refresh.assert_not_awaited()+++async def test_refresh_command_disconnects_and_propagates_failure(monkeypatch):+ db = SimpleNamespace(connect=AsyncMock(), disconnect=AsyncMock())+ monkeypatch.setattr(e2e_test_data, "prisma", db)+ monkeypatch.setattr(+ e2e_test_data,+ "refresh_seeded_credentials",+ AsyncMock(side_effect=ValueError("invalid seeded credential")),+ )+ monkeypatch.setattr("sys.argv", ["e2e_test_data.py", "--refresh-credentials-only"])+ with pytest.raises(ValueError, match="invalid seeded credential"):+ await e2e_test_data.main()+ db.disconnect.assert_awaited_once()diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/page.test.tsxindex 3603a5bc08..06bb4ba078 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/page.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/page.test.tsx@@ -1,4 +1,5 @@import type { ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";import {render,screen,@@ -69,4 +70,30 @@ describe("SignupPage", () => {await screen.findByText("User with this email already exists"),).toBeDefined();});++ test("does not server-render an interactive form before auth initializes", () => {+ const markup = renderToStaticMarkup(<SignupPage />);++ expect(markup).not.toContain('id="password"');+ expect(markup).not.toContain('type="submit"');+ });++ test("preserves form input during a background auth refresh", () => {+ const { rerender } = render(<SignupPage />);++ fireEvent.change(screen.getByLabelText("Email"), {+ target: { value: "[email protected]" },+ });++ mockUseAuth.mockReturnValue({+ user: null,+ isUserLoading: true,+ isLoggedIn: false,+ });+ rerender(<SignupPage />);++ expect((screen.getByLabelText("Email") as HTMLInputElement).value).toBe(+ "[email protected]",+ );+ });});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/signup/page.tsxindex 9e3a22c858..db954f9c4d 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/page.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/page.tsx@@ -40,17 +40,17 @@ export default function SignupPage() {form,feedback,isLoggedIn,+ hasInitializedAuth,isLoading,isGoogleLoading,isCloudEnv,- isUserLoading,showNotAllowedModal,handleSubmit,handleProviderSignup,handleCloseNotAllowedModal,} = useSignupPage();- if (isUserLoading || isLoggedIn) {+ if (!hasInitializedAuth || isLoggedIn) {return <LoadingSignup />;}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/useSignupPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/signup/useSignupPage.tsindex 79b2ff6277..a1553b20f2 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/useSignupPage.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/useSignupPage.ts@@ -15,6 +15,7 @@ export function useSignupPage() {useCaptureMarketingPrompt();const { user, isUserLoading, isLoggedIn } = useAuth();+ const [hasInitializedAuth, setHasInitializedAuth] = useState(false);const [feedback, setFeedback] = useState<string | null>(null);const { toast } = useToast();const router = useRouter();@@ -29,6 +30,12 @@ export function useSignupPage() {// `/signup?next=https://phishing.site` cannot redirect users elsewhere.const nextUrl = sanitizeAuthNext(searchParams.get("next"));+ useEffect(() => {+ if (!isUserLoading) {+ setHasInitializedAuth(true);+ }+ }, [isUserLoading]);+// Only honour explicit `?next=` deep links here. Generic "already logged in// on /signup, get me out" is handled by OnboardingProvider so the user lands// straight on /onboarding or /copilot. Otherwise we'd bounce@@ -160,6 +167,7 @@ export function useSignupPage() {form,feedback,isLoggedIn: !!user,+ hasInitializedAuth,isLoading,isGoogleLoading,isCloudEnv,diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/first-run.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/first-run.test.tsxnew file mode 100644index 0000000000..74bfa7d544--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/first-run.test.tsx@@ -0,0 +1,215 @@+import {+ getGetV1GetExecutionDetailsMockHandler,+ getGetV1GetExecutionDetailsResponseMock,+ getGetV1ListGraphExecutionsMockHandler,+ getPostV1ExecuteGraphAgentMockHandler,+ getPostV1ExecuteGraphAgentResponseMock,+} from "@/app/api/__generated__/endpoints/graphs/graphs.msw";+import {+ getGetV2GetLibraryAgentMockHandler,+ getGetV2GetLibraryAgentResponseMock,+} from "@/app/api/__generated__/endpoints/library/library.msw";+import {+ getGetV2GetASpecificPresetResponseMock,+ getGetV2ListPresetsMockHandler,+} from "@/app/api/__generated__/endpoints/presets/presets.msw";+import {+ getGetV1ListExecutionSchedulesForAGraphMockHandler,+ getPostV1CreateExecutionScheduleResponseMock,+} from "@/app/api/__generated__/endpoints/schedules/schedules.msw";+import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";+import { server } from "@/mocks/mock-server";+import { render, screen, waitFor } from "@/tests/integrations/test-utils";+import userEvent from "@testing-library/user-event";+import { NuqsTestingAdapter } from "nuqs/adapters/testing";+import { expect, test, vi } from "vitest";+import { NewAgentLibraryView } from "../components/NewAgentLibraryView/NewAgentLibraryView";+import { useNewAgentLibraryView } from "../components/NewAgentLibraryView/useNewAgentLibraryView";++vi.mock("next/navigation", async (importOriginal) => ({+ ...(await importOriginal<typeof import("next/navigation")>()),+ useParams: () => ({ id: "library-agent" }),+ usePathname: () => "/library/agents/library-agent",+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }),+ useSearchParams: () => new URLSearchParams(),+}));++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({+ user: { id: "user-1", email: "[email protected]" },+ isLoggedIn: true,+ isUserLoading: false,+ }),+}));++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >()),+ useGetFlag: () => false,+ useFlagStatus: () => ({ enabled: false, ready: true }),+}));++test("selects the first created run while the sidebar still has an empty cached list", async () => {+ const run = getPostV1ExecuteGraphAgentResponseMock({+ id: "new-run",+ graph_id: "graph-1",+ graph_version: 1,+ status: AgentExecutionStatus.COMPLETED,+ inputs: {},+ credential_inputs: {},+ nodes_input_masks: {},+ preset_id: null,+ stats: null,+ });+ const executionRequests = vi.fn(() => run);+ const detailRequests = vi.fn(() => ({+ ...getGetV1GetExecutionDetailsResponseMock(),+ ...run,+ inputs: {},+ outputs: {},+ node_executions: [],+ }));+ server.use(+ getGetV2GetLibraryAgentMockHandler(+ getGetV2GetLibraryAgentResponseMock({+ id: "library-agent",+ graph_id: "graph-1",+ graph_version: 1,+ name: "First run agent",+ input_schema: { type: "object", properties: {} },+ credentials_input_schema: { type: "object", properties: {} },+ has_external_trigger: false,+ trigger_setup_info: null,+ has_sensitive_action: false,+ has_human_in_the_loop: false,+ recommended_schedule_cron: null,+ }),+ ),+ getGetV1ListGraphExecutionsMockHandler({+ executions: [],+ pagination: {+ total_items: 0,+ total_pages: 0,+ current_page: 1,+ page_size: 20,+ },+ }),+ getGetV1ListExecutionSchedulesForAGraphMockHandler([]),+ getGetV2ListPresetsMockHandler({+ presets: [],+ pagination: {+ total_items: 0,+ total_pages: 0,+ current_page: 1,+ page_size: 100,+ },+ }),+ getPostV1ExecuteGraphAgentMockHandler(executionRequests),+ getGetV1GetExecutionDetailsMockHandler(detailRequests),+ );++ render(+ <NuqsTestingAdapter hasMemory>+ <NewAgentLibraryView />+ </NuqsTestingAdapter>,+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Setup your task" }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Start Task" }),+ );+ await waitFor(() => expect(executionRequests).toHaveBeenCalledOnce());++ await waitFor(() => expect(detailRequests).toHaveBeenCalled());+ expect(await screen.findByRole("button", { name: "Output" })).toBeDefined();+ expect(screen.queryByRole("button", { name: "Setup your task" })).toBeNull();+});++interface Props {+ type: "scheduled" | "triggers";+}++function CreatedItemProbe({ type }: Props) {+ const view = useNewAgentLibraryView();++ function createItem() {+ if (type === "scheduled") {+ view.onScheduleCreated(+ getPostV1CreateExecutionScheduleResponseMock({ id: "new-item" }),+ );+ } else {+ view.onTriggerSetup(+ getGetV2GetASpecificPresetResponseMock({+ id: "new-item",+ webhook_id: "webhook-1",+ }),+ );+ }+ }++ function reportEmptyCounts() {+ view.handleCountsChange({+ runsCount: 0,+ schedulesCount: 0,+ templatesCount: 0,+ triggersCount: 0,+ loading: false,+ hasError: false,+ });+ }++ return (+ <>+ <button disabled={!view.ready} onClick={createItem}>+ Create item+ </button>+ <button onClick={reportEmptyCounts}>Refresh empty counts</button>+ <output>{`${view.activeTab}:${view.activeItemId}`}</output>+ </>+ );+}++test.each(["scheduled", "triggers"] as const)(+ "keeps a newly created %s item selected when empty counts arrive",+ async (type) => {+ server.use(+ getGetV2GetLibraryAgentMockHandler(+ getGetV2GetLibraryAgentResponseMock({+ id: "library-agent",+ graph_id: "graph-1",+ }),+ ),+ getGetV1ListExecutionSchedulesForAGraphMockHandler([]),+ getGetV2ListPresetsMockHandler({+ presets: [],+ pagination: {+ total_items: 0,+ total_pages: 0,+ current_page: 1,+ page_size: 100,+ },+ }),+ );+ const onUrlUpdate = vi.fn();+ render(+ <NuqsTestingAdapter hasMemory onUrlUpdate={onUrlUpdate}>+ <CreatedItemProbe type={type} />+ </NuqsTestingAdapter>,+ );+ const create = screen.getByRole("button", { name: "Create item" });+ await waitFor(() => expect(create.hasAttribute("disabled")).toBe(false));+ await userEvent.click(create);+ await userEvent.click(+ screen.getByRole("button", { name: "Refresh empty counts" }),+ );+ await waitFor(() => {+ expect(screen.getByRole("status").textContent).toBe(`${type}:new-item`);+ const update = onUrlUpdate.mock.lastCall?.[0];+ expect(update?.searchParams.get("activeItem")).toBe(+ type === "triggers" ? "preset:new-item" : "new-item",+ );+ });+ },+);diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/helpers.test.tsindex f61b12950e..22b330bb8e 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/helpers.test.ts@@ -3,10 +3,65 @@ import { describe, expect, test } from "vitest";import {activeItemParamFor,deriveSelectedTriggerKind,+ isNewAgentTaskDisabled,parseActiveItemParam,retryUnlessClientError,} from "../components/NewAgentLibraryView/helpers";+describe("new agent task availability", () => {+ test("stays disabled while the sidebar layout can still change", () => {+ expect(+ isNewAgentTaskDisabled({+ sidebarLoading: true,+ isTemplateLoading: false,+ activeTab: "runs",+ }),+ ).toBe(true);+ });++ test("stays disabled while the selected template is loading", () => {+ expect(+ isNewAgentTaskDisabled({+ sidebarLoading: false,+ isTemplateLoading: true,+ activeTab: "templates",+ }),+ ).toBe(true);+ });++ test("is enabled after the active layout data is stable", () => {+ expect(+ isNewAgentTaskDisabled({+ sidebarLoading: false,+ isTemplateLoading: false,+ activeTab: "runs",+ }),+ ).toBe(false);+ });++ test("is enabled when sidebar data failed instead of loading forever", () => {+ expect(+ isNewAgentTaskDisabled({+ sidebarLoading: true,+ sidebarHasError: true,+ isTemplateLoading: false,+ activeTab: "runs",+ }),+ ).toBe(false);+ });++ test("still waits for the selected template when sidebar data failed", () => {+ expect(+ isNewAgentTaskDisabled({+ sidebarLoading: true,+ sidebarHasError: true,+ isTemplateLoading: true,+ activeTab: "templates",+ }),+ ).toBe(true);+ });+});+describe("activeItem param prefix contract", () => {test("round-trips both kinds and passes through bare IDs and null", () => {for (const kind of ["trigger-agent", "webhook-trigger"] as const) {diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/trigger-agents.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/trigger-agents.test.tsxindex 6fe85428fb..604597b59a 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/trigger-agents.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/trigger-agents.test.tsx@@ -4,9 +4,16 @@ import {getGetV2GetLibraryAgentMockHandler,getGetV2GetLibraryAgentResponseMock,getGetV2ListTriggerAgentsMockHandler,+ getGetV2ListTriggerAgentsMockHandler422,} from "@/app/api/__generated__/endpoints/library/library.msw";-import { getGetV1ListGraphExecutionsMockHandler } from "@/app/api/__generated__/endpoints/graphs/graphs.msw";-import { getGetV1ListExecutionSchedulesForAGraphMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";+import {+ getGetV1ListGraphExecutionsMockHandler,+ getGetV1ListGraphExecutionsMockHandler422,+} from "@/app/api/__generated__/endpoints/graphs/graphs.msw";+import {+ getGetV1ListExecutionSchedulesForAGraphMockHandler,+ getGetV1ListExecutionSchedulesForAGraphMockHandler422,+} from "@/app/api/__generated__/endpoints/schedules/schedules.msw";import {getGetV2GetASpecificPresetMockHandler,getGetV2GetASpecificPresetResponseMock,@@ -19,7 +26,13 @@ import { BackendAPIProvider } from "@/lib/autogpt-server-api/context";import OnboardingProvider from "@/providers/onboarding/onboarding-provider";import { server } from "@/mocks/mock-server";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";import userEvent from "@testing-library/user-event";import { http, HttpResponse } from "msw";import { NuqsTestingAdapter } from "nuqs/adapters/testing";@@ -27,6 +40,9 @@ import { ReactNode } from "react";import { beforeEach, describe, expect, test, vi } from "vitest";import { NewAgentLibraryView } from "../components/NewAgentLibraryView/NewAgentLibraryView";import { PRESETS_PAGE_SIZE } from "../components/NewAgentLibraryView/hooks/useAgentPresetsQuery";+import { SidebarRunsList } from "../components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList";+import { getGetV1ListGraphExecutionsQueryKey } from "@/app/api/__generated__/endpoints/graphs/graphs";+import { getGetV1ListExecutionSchedulesForAGraphQueryKey } from "@/app/api/__generated__/endpoints/schedules/schedules";const PARENT_ID = "parent-agent-id";const PARENT_GRAPH_ID = "parent-graph-id";@@ -78,10 +94,13 @@ vi.mock("@/services/feature-flags/use-get-flag", () => ({// Per-test render wrapper so we can set the nuqs initial URL state// (e.g. activeTab=triggers) — Radix tab clicks don't always round-trip// through the NuqsTestingAdapter within a single sync frame.-function renderWithInitialParams(ui: ReactNode, searchParams = "") {- const queryClient = new QueryClient({+function renderWithInitialParams(+ ui: ReactNode,+ searchParams = "",+ queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },- });+ }),+) {return render(<QueryClientProvider client={queryClient}><NuqsTestingAdapter searchParams={searchParams}>@@ -173,6 +192,119 @@ describe("Library agent view — trigger agents", () => {mockUseGetFlag.mockReturnValue(true);});+ test.each([+ ["run history", getGetV1ListGraphExecutionsMockHandler422],+ ["schedules", getGetV1ListExecutionSchedulesForAGraphMockHandler422],+ ["presets", getGetV2ListPresetsMockHandler422],+ ["trigger agents", getGetV2ListTriggerAgentsMockHandler422],+ ])(+ "keeps new agent tasks available when %s fails",+ async (_name, errorHandler) => {+ server.use(+ ...baseHandlers({+ input_schema: {},+ credentials_input_schema: {},+ has_external_trigger: false,+ recommended_schedule_cron: "0 9 * * *",+ }),+ emptyPresetsHandler,+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([]),+ );+ server.use(errorHandler());++ renderWithInitialParams(<NewAgentLibraryView />);++ await screen.findByText(/when retrieving data/i);+ expect(+ await screen.findByText(+ "Use Try Again in the sidebar to reload your tasks.",+ ),+ ).toBeDefined();+ expect(screen.getByRole("button", { name: /try again/i })).toBeDefined();+ const newTaskButton = screen.getByRole("button", {+ name: "New agent task",+ });+ await waitFor(() => {+ expect(newTaskButton.hasAttribute("disabled")).toBe(false);+ });+ await userEvent.click(newTaskButton);+ expect(await screen.findByRole("dialog")).toBeDefined();+ await userEvent.keyboard("{Escape}");+ server.use(+ ...baseHandlers(),+ emptyPresetsHandler,+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([]),+ );+ await userEvent.click(screen.getByRole("button", { name: /try again/i }));+ await waitFor(() => {+ expect(+ screen.queryByText(+ "Use Try Again in the sidebar to reload your tasks.",+ ),+ ).toBeNull();+ expect(screen.queryByTestId("loading-selected-content")).toBeNull();+ });+ },+ );++ test("notifies the parent after recovery while another sidebar query stays stale", async () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: 60_000 } },+ });+ const onCountsChange = vi.fn();+ const schedulesKey =+ getGetV1ListExecutionSchedulesForAGraphQueryKey(PARENT_GRAPH_ID);+ server.use(+ ...baseHandlers(),+ emptyPresetsHandler,+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([]),+ );+ server.use(getGetV1ListGraphExecutionsMockHandler422());++ renderWithInitialParams(+ <SidebarRunsList+ agent={getGetV2GetLibraryAgentResponseMock({+ id: PARENT_ID,+ graph_id: PARENT_GRAPH_ID,+ })}+ onSelectRun={vi.fn()}+ onCountsChange={onCountsChange}+ />,+ "",+ queryClient,+ );++ await waitFor(() => {+ expect(onCountsChange).toHaveBeenLastCalledWith(+ expect.objectContaining({ hasError: true, loading: true }),+ );+ expect(queryClient.getQueryState(schedulesKey)?.status).toBe("success");+ });+ await act(async () => {+ await queryClient.invalidateQueries({+ queryKey: schedulesKey,+ refetchType: "none",+ });+ });+ server.use(...baseHandlers());+ await act(async () => {+ await queryClient.refetchQueries({+ queryKey: getGetV1ListGraphExecutionsQueryKey(PARENT_GRAPH_ID),+ });+ });++ await waitFor(() => {+ expect(onCountsChange).toHaveBeenLastCalledWith(+ expect.objectContaining({ hasError: false, loading: false }),+ );+ });+ expect(queryClient.getQueryState(schedulesKey)?.isInvalidated).toBe(true);+ expect(screen.queryByText(/when retrieving data/i)).toBeNull();+ });+test("hides Triggers tab when there are no trigger agents and no webhook triggers", async () => {server.use(...baseHandlers(),@@ -490,7 +622,7 @@ describe("Library agent view — trigger agents", () => {);await screen.findByText("Trigger Details");- screen.getByDisplayValue("Webhook Trigger");+ await screen.findByDisplayValue("Webhook Trigger");});test("agent:-prefixed activeItem renders the trigger agent detail view", async () => {@@ -586,7 +718,7 @@ describe("Library agent view — trigger agents", () => {// The detail view renders from the hint alone — both list queries are// still gated at this point.await screen.findByText("Trigger Details");- screen.getByDisplayValue("Hint Routed Early");+ await screen.findByDisplayValue("Hint Routed Early");releaseLists();});@@ -665,7 +797,7 @@ describe("Library agent view — trigger agents", () => {{ timeout: 5000 },);await screen.findByText("Trigger Details", undefined, { timeout: 5000 });- screen.getByDisplayValue("Beyond Page Trigger");+ await screen.findByDisplayValue("Beyond Page Trigger");expect(screen.queryByText("Trigger not found")).toBeNull();});@@ -779,7 +911,7 @@ describe("Library agent view — trigger agents", () => {// Paging through the full cap before the by-ID fallback resolves the detail// is a long async chain, so allow extra time.await screen.findByText("Trigger Details", undefined, { timeout: 8000 });- screen.getByDisplayValue("Beyond Cap Trigger");+ await screen.findByDisplayValue("Beyond Cap Trigger");// The beyond-cap fallback fired the by-ID fetch it's meant to.expect(presetGetCalls).toBeGreaterThan(0);});diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/NewAgentLibraryView.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/NewAgentLibraryView.tsxindex 0b4a167587..01d6a5e780 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/NewAgentLibraryView.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/NewAgentLibraryView.tsx@@ -26,7 +26,10 @@ import { SelectedTriggerView } from "./components/selected-views/SelectedTriggerimport { SelectedViewLayout } from "./components/selected-views/SelectedViewLayout";import { SidebarRunsList } from "./components/sidebar/SidebarRunsList/SidebarRunsList";import { usePlatformChrome } from "@/app/(platform)/PlatformChrome/usePlatformChrome";-import { AGENT_LIBRARY_SECTION_PADDING_X } from "./helpers";+import {+ AGENT_LIBRARY_SECTION_PADDING_X,+ isNewAgentTaskDisabled,+} from "./helpers";import { useMarketplaceUpdate } from "./hooks/useMarketplaceUpdate";import { useNewAgentLibraryView } from "./useNewAgentLibraryView";import { PlusSignIcon } from "@hugeicons/core-free-icons";@@ -45,6 +48,7 @@ export function NewAgentLibraryView() {selectedTriggerKind,retryTriggerLists,sidebarLoading,+ sidebarHasError,activeTab,setActiveTab,handleSelectRun,@@ -257,7 +261,12 @@ export function NewAgentLibraryView() {variant="outline"size="small"className="w-full"- disabled={isTemplateLoading && activeTab === "templates"}+ disabled={isNewAgentTaskDisabled({+ sidebarLoading,+ sidebarHasError,+ isTemplateLoading,+ activeTab,+ })}><Icon icon={PlusSignIcon} size={16} /> New agent task</Button>@@ -313,6 +322,16 @@ export function NewAgentLibraryView() {banner={renderMarketplaceUpdateBanner()}/>)+ ) : sidebarHasError ? (+ <SelectedViewLayout+ agent={agent}+ banner={renderMarketplaceUpdateBanner()}+ >+ <ErrorCard+ context="agent tasks"+ hint="Use Try Again in the sidebar to reload your tasks."+ />+ </SelectedViewLayout>) : sidebarLoading ? (<LoadingSelectedContent agent={agent} />) : activeTab === "scheduled" ? (diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsxindex dbeb1caa33..ce1dcef15d 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsx@@ -40,6 +40,7 @@ interface Props {templatesCount: number;triggersCount: number;loading?: boolean;+ hasError?: boolean;}) => void;}@@ -64,6 +65,7 @@ export function SidebarRunsList({triggersCount,error,loading,+ retryFailedQueries,fetchMoreRuns,hasMoreRuns,isFetchingMoreRuns,@@ -75,7 +77,7 @@ export function SidebarRunsList({});if (error) {- return <ErrorCard responseError={error} />;+ return <ErrorCard responseError={error} onRetry={retryFailedQueries} />;}if (loading) {diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/useSidebarRunsList.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/useSidebarRunsList.tsindex 5fa8acff71..ebb3f0f5f6 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/useSidebarRunsList.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/useSidebarRunsList.ts@@ -49,6 +49,7 @@ type Args = {templatesCount: number;triggersCount: number;loading?: boolean;+ hasError?: boolean;}) => void;};@@ -130,11 +131,20 @@ export function useSidebarRunsList({!schedulesQuery.isSuccess ||!presetsQuery.presetsSettled ||(triggerAgentsEnabled && !triggerAgentsQuery.isSuccess);- const stale =- runsQuery.isStale ||- schedulesQuery.isStale ||- presetsQuery.isStale ||- (triggerAgentsEnabled && triggerAgentsQuery.isStale);+ const error =+ schedulesQuery.error ||+ runsQuery.error ||+ presetsQuery.error ||+ (triggerAgentsEnabled ? triggerAgentsQuery.error : null);++ function retryFailedQueries() {+ if (runsQuery.isError) void runsQuery.refetch();+ if (schedulesQuery.isError) void schedulesQuery.refetch();+ if (presetsQuery.isError) void presetsQuery.refetch();+ if (triggerAgentsEnabled && triggerAgentsQuery.isError) {+ void triggerAgentsQuery.refetch();+ }+ }// Update query cache when execution events arrive via websocketuseExecutionEvents({@@ -151,13 +161,14 @@ export function useSidebarRunsList({// Notify parent about counts and loading stateuseEffect(() => {- if (onCountsChange && !stale) {+ if (onCountsChange) {onCountsChange({runsCount,schedulesCount,templatesCount,triggersCount,loading,+ hasError: !!error,});}}, [@@ -167,7 +178,7 @@ export function useSidebarRunsList({templatesCount,triggersCount,loading,- stale,+ error,]);useEffect(() => {@@ -210,13 +221,10 @@ export function useSidebarRunsList({templates,triggers,triggerAgents,- error:- schedulesQuery.error ||- runsQuery.error ||- presetsQuery.error ||- (triggerAgentsEnabled ? triggerAgentsQuery.error : null),+ error,loading,runsQuery,+ retryFailedQueries,tabValue,runsCount,schedulesCount,diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/helpers.tsindex 0861314a35..787b995b4c 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/helpers.ts@@ -11,6 +11,18 @@ export type SelectedTriggerKind =| "error"| "not-found";+export function isNewAgentTaskDisabled(args: {+ sidebarLoading: boolean;+ sidebarHasError?: boolean;+ isTemplateLoading: boolean;+ activeTab: string;+}): boolean {+ return (+ (args.sidebarLoading && !args.sidebarHasError) ||+ (args.isTemplateLoading && args.activeTab === "templates")+ );+}+// Optional type-hint prefixes for `activeItem` values on the Triggers tab,// so the right detail view can render without waiting for the item lists.// Bare IDs (old links, other tabs) parse with a null hint and are resolveddiff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/useNewAgentLibraryView.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/useNewAgentLibraryView.tsindex bb2085ee42..96223ca943 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/useNewAgentLibraryView.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/useNewAgentLibraryView.ts@@ -13,6 +13,7 @@ import { useParams } from "next/navigation";import { parseAsString, useQueryStates } from "nuqs";import { useCallback, useEffect, useMemo, useState } from "react";import {+ activeItemParamFor,deriveSelectedTriggerKind,parseActiveItemParam,retryUnlessClientError,@@ -108,6 +109,7 @@ export function useNewAgentLibraryView() {});const [sidebarLoading, setSidebarLoading] = useState(true);+ const [sidebarHasError, setSidebarHasError] = useState(false);const hasAnyItems = useMemo(() =>@@ -219,6 +221,7 @@ export function useNewAgentLibraryView() {templatesCount: number;triggersCount: number;loading?: boolean;+ hasError?: boolean;}) => {setSidebarCounts({runsCount: counts.runsCount,@@ -229,6 +232,9 @@ export function useNewAgentLibraryView() {if (counts.loading !== undefined) {setSidebarLoading(counts.loading);}+ if (counts.hasError !== undefined) {+ setSidebarHasError(counts.hasError);+ }},[],);@@ -239,16 +245,12 @@ export function useNewAgentLibraryView() {| { type: "triggers"; item: LibraryAgentPreset }| { type: "scheduled"; item: GraphExecutionJobInfo },) {- if (!hasAnyItems) {- // Manually increment item count to flip hasAnyItems and showSidebarLayout- const counts = {- runsCount: createEvent.type === "runs" ? 1 : 0,- triggersCount: createEvent.type === "triggers" ? 1 : 0,- schedulesCount: createEvent.type === "scheduled" ? 1 : 0,- templatesCount: 0,- };- handleCountsChange(counts);- }+ handleSelectRun(+ createEvent.type === "triggers"+ ? activeItemParamFor("webhook-trigger", createEvent.item.id)+ : createEvent.item.id,+ createEvent.type,+ );}function onRunInitiated(newRun: GraphExecutionMeta) {@@ -301,6 +303,7 @@ export function useNewAgentLibraryView() {retryTriggerLists,sidebarLoading,activeTab,+ sidebarHasError,setActiveTab: handleSetActiveTab,handleClearSelectedRun,handleScheduleDeleted,diff --git a/autogpt_platform/frontend/src/playwright/marketplace-happy-path.spec.ts b/autogpt_platform/frontend/src/playwright/marketplace-happy-path.spec.tsindex f81386ea40..23fe9f30ee 100644--- a/autogpt_platform/frontend/src/playwright/marketplace-happy-path.spec.ts+++ b/autogpt_platform/frontend/src/playwright/marketplace-happy-path.spec.ts@@ -30,8 +30,10 @@ test("marketplace happy path: user can add a Marketplace agent to Library and ruconst agentName = await page.getByTestId("agent-title").innerText();- await page.getByTestId("agent-add-library-button").click();- await expect(page.getByText("Redirecting to your library...")).toBeVisible();+ await Promise.all([+ expect(page.getByText("Redirecting to your library...")).toBeVisible(),+ page.getByTestId("agent-add-library-button").click(),+ ]);await expect(page).toHaveURL(/\/library\/agents\//);const libraryPage = new LibraryPage(page);diff --git a/autogpt_platform/frontend/src/playwright/pages/library.page.ts b/autogpt_platform/frontend/src/playwright/pages/library.page.tsindex 6e1efa178f..c9d097aa5b 100644--- a/autogpt_platform/frontend/src/playwright/pages/library.page.ts+++ b/autogpt_platform/frontend/src/playwright/pages/library.page.ts@@ -1080,26 +1080,48 @@ export async function importAgentFromFile(.then(() => true).catch(() => false);if (sawUploadingState) {- await expect- .poll(- async () => {- if (/\/build/.test(page.url())) {- return "build";- }- if (!(await uploadingButton.isVisible().catch(() => false))) {- return "gone";- }- return (await uploadingButton.isDisabled().catch(() => false))- ? "disabled"- : "enabled";- },- {- timeout: 5000,- message:- 'upload button should either stay disabled while "Uploading..." is visible or disappear because navigation already started',- },- )- .not.toBe("enabled");+ const uploadingState = await uploadingButton+ .evaluateAll((buttons) => {+ const visibleButton = buttons.find((button) => {+ const { width, height } = button.getBoundingClientRect();+ return (+ width > 0 &&+ height > 0 &&+ window.getComputedStyle(button).visibility !== "hidden"+ );+ });+ if (!visibleButton) {+ return "gone" as const;+ }+ return visibleButton.matches(":disabled") ||+ visibleButton.getAttribute("aria-disabled") === "true"+ ? ("disabled" as const)+ : ("enabled" as const);+ })+ .catch(async (error: unknown) => {+ if (+ !(error instanceof Error) ||+ !error.message.includes("Execution context was destroyed")+ ) {+ throw error;+ }+ if (!/\/build/.test(page.url())) {+ await page+ .waitForURL(/\/build/, {+ timeout: 500,+ waitUntil: "commit",+ })+ .catch(() => {+ throw error;+ });+ }+ return "build" as const;+ });++ expect(+ uploadingState,+ 'upload button should be disabled while "Uploading..." is visible',+ ).not.toBe("enabled");}// Upload → backend creates the graph → router pushes /build?flowID=...diff --git a/autogpt_platform/frontend/src/playwright/utils/signup.ts b/autogpt_platform/frontend/src/playwright/utils/signup.tsindex 7a2a3abd6b..0b6ddf8df4 100644--- a/autogpt_platform/frontend/src/playwright/utils/signup.ts+++ b/autogpt_platform/frontend/src/playwright/utils/signup.ts@@ -3,6 +3,7 @@ import { getSelectors } from "./selectors";import { isVisible } from "./assertion";import { BuildPage } from "../pages/build.page";import { skipOnboardingIfPresent } from "./onboarding";+import { expect } from "@playwright/test";export async function signupTestUser(page: any,@@ -21,12 +22,13 @@ export async function signupTestUser(// Navigate to signup pageawait page.goto("/signup");- // Wait for page to load- getText("Create a new account");+ // Wait for the hydrated form, not the server-rendered loading shell.+ await getText("Create your account").waitFor({ state: "visible" });// Fill formconst emailInput = getField("Email");await emailInput.fill(userEmail);+ await expect(emailInput).toHaveValue(userEmail);const passwordInput = page.locator("#password");await passwordInput.fill(userPassword);const confirmPasswordInput = page.locator("#confirmPassword");