Skip to content

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.

feat(platform): fire an expert with clean archive UX (#14029)

Abhimanyu Yadav888f0fe1557a
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index fb3d2be261..99a57b3ba0 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -165,6 +165,32 @@ async def _validate_and_get_session(
return session
+async def _validate_session_expert_writable_by_user(
+ session: ChatSessionInfo,
+ user_id: str,
+) -> None:
+ """Reject writes to an expert session *user_id* may no longer write to.
+
+ A plain (non-expert) session is always writable and returns early. For an
+ expert session the expert has to still be owned by *user_id* and still be
+ hired — fired, template, deleted, and other people's experts all fail, and
+ all fail as the same non-enumerable 404.
+ """
+ if session.expert_id is None:
+ return
+ if not await experts_db.owns_active_expert(user_id, session.expert_id):
+ raise HTTPException(status_code=404, detail="Expert not found")
+
+
+async def _validate_and_get_writable_session(
+ session_id: str,
+ user_id: str,
+) -> ChatSessionInfo:
+ session = await _validate_and_get_session(session_id, user_id)
+ await _validate_session_expert_writable_by_user(session, user_id)
+ return session
+
+
# Minimum age before the orphan-reset paths (``get_session`` and
# ``cancel_session_task``) will touch a ``chatStatus='running'`` session
# that has no live Redis stream. Lower bound has to clear the
@@ -1412,6 +1438,21 @@ async def stream_chat_post(
"""
import time
+ stream_start_time = time.perf_counter()
+ # Wall-clock arrival time, propagated to the executor so the turn-start
+ # drain can order pending messages relative to this request (pending
+ # pushed BEFORE this instant were typed earlier; pending pushed AFTER
+ # are race-path follow-ups typed while /stream was still processing).
+ request_arrival_at = time.time()
+ log_meta = {"component": "ChatStream", "session_id": session_id, "user_id": user_id}
+
+ logger.info(
+ f"[TIMING] stream_chat_post STARTED, session={session_id}, "
+ f"user={user_id}, message_len={len(request.message)}",
+ extra={"json_fields": log_meta},
+ )
+ session = await _validate_and_get_writable_session(session_id, user_id)
+
# Fire-and-forget; per-user Redis dedup inside the helper provides
# cross-process / cross-restart idempotency. Same pattern as
# graphiti/ingest.py's ensure_dream_system_scheduled registration.
@@ -1426,20 +1467,6 @@ async def stream_chat_post(
name=f"morning-briefing-register-{user_id[:12]}",
)
- stream_start_time = time.perf_counter()
- # Wall-clock arrival time, propagated to the executor so the turn-start
- # drain can order pending messages relative to this request (pending
- # pushed BEFORE this instant were typed earlier; pending pushed AFTER
- # are race-path follow-ups typed while /stream was still processing).
- request_arrival_at = time.time()
- log_meta = {"component": "ChatStream", "session_id": session_id, "user_id": user_id}
-
- logger.info(
- f"[TIMING] stream_chat_post STARTED, session={session_id}, "
- f"user={user_id}, message_len={len(request.message)}",
- extra={"json_fields": log_meta},
- )
- session = await _validate_and_get_session(session_id, user_id)
is_platform_route = session.metadata.llm_auth_provider == "platform"
if is_platform_route:
await enforce_payment_paywall(user_id)
@@ -1819,7 +1846,7 @@ async def queue_pending_message(
user_id: str = Security(auth.get_user_id),
):
"""Queue a follow-up message while the session has an active turn."""
- session = await _validate_and_get_session(session_id, user_id)
+ session = await _validate_and_get_writable_session(session_id, user_id)
if session.metadata.llm_auth_provider == "codex":
await enforce_codex_access_http(user_id)
try:
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
index 84b5b2939d..024c743256 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -288,6 +288,14 @@ def _mock_stream_internals(
new_callable=AsyncMock,
return_value=False,
)
+ # The write gate only queries when ``session.expert_id`` is set; default it
+ # to "still hired" so expert-scoped tests reach the logic they care about.
+ # The gate's own tests re-patch this with the verdict they need.
+ mock_owns_active_expert = mocker.patch(
+ "backend.api.features.chat.routes.experts_db.owns_active_expert",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
mocker.patch(
"backend.api.features.chat.routes.chat_message_has_assistant_reply",
new_callable=AsyncMock,
@@ -318,6 +326,7 @@ def _mock_stream_internals(
enqueue=mock_schedule,
paywall=mock_paywall,
session=mock_session,
+ owns_active_expert=mock_owns_active_expert,
)
@@ -347,6 +356,58 @@ def test_stream_chat_accepts_20_file_ids(mocker: pytest_mock.MockerFixture):
assert response.status_code == 200
+def test_stream_chat_allows_an_active_expert_session(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mocks = _mock_stream_internals(mocker)
+ mocks.session.expert_id = "expert-active"
+ active_check = mocks.owns_active_expert
+
+ response = client.post(
+ "/sessions/sess-1/stream",
+ json={"message": "keep working"},
+ )
+
+ assert response.status_code == 200
+ active_check.assert_awaited_once_with(test_user_id, "expert-active")
+ mocks.enqueue.assert_awaited_once()
+
+
+def test_stream_chat_rejects_an_archived_expert_session(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mocks = _mock_stream_internals(mocker)
+ mocks.session.expert_id = "expert-archived"
+ active_check = mocks.owns_active_expert
+ active_check.return_value = False
+
+ response = client.post(
+ "/sessions/sess-1/stream",
+ json={"message": "keep working"},
+ )
+
+ assert response.status_code == 404
+ active_check.assert_awaited_once_with(test_user_id, "expert-archived")
+ mocks.enqueue.assert_not_awaited()
+ mocks.paywall.assert_not_awaited()
+
+
+def test_stream_chat_skips_the_expert_gate_for_a_non_expert_session(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """Plain Autopilot turns must not pay for the write-gate's extra query."""
+ mocks = _mock_stream_internals(mocker)
+ mocks.session.expert_id = None
+
+ response = client.post("/sessions/sess-1/stream", json={"message": "hello"})
+
+ assert response.status_code == 200
+ mocks.owns_active_expert.assert_not_awaited()
+ mocks.enqueue.assert_awaited_once()
+
+
# ─── Duplicate message dedup ──────────────────────────────────────────
@@ -1760,6 +1821,7 @@ def _mock_stream_queue_internals(
if session_exists:
mock_session = mocker.MagicMock()
mock_session.id = "sess-1"
+ mock_session.expert_id = None
mocker.patch(
"backend.api.features.chat.routes._validate_and_get_session",
new_callable=AsyncMock,
@@ -1807,6 +1869,7 @@ def _mock_stream_queue_internals(
new_callable=AsyncMock,
return_value=None,
)
+ return mock_session if session_exists else None
def test_queue_pending_message_returns_200_when_turn_in_flight(
@@ -1839,6 +1902,72 @@ def test_queue_pending_message_session_not_found_returns_404(
assert response.status_code == 404
+def test_queue_pending_message_allows_an_active_expert_session(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mock_session = _mock_stream_queue_internals(mocker)
+ assert mock_session is not None
+ mock_session.expert_id = "expert-active"
+ active_check = mocker.patch(
+ "backend.api.features.chat.routes.experts_db.owns_active_expert",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+
+ response = client.post(
+ "/sessions/sess-1/messages/pending",
+ json={"message": "follow-up"},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["buffer_length"] == 1
+ active_check.assert_awaited_once_with(test_user_id, "expert-active")
+
+
+def test_queue_pending_message_rejects_an_archived_expert_session(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mock_session = _mock_stream_queue_internals(mocker)
+ assert mock_session is not None
+ mock_session.expert_id = "expert-archived"
+ active_check = mocker.patch(
+ "backend.api.features.chat.routes.experts_db.owns_active_expert",
+ new_callable=AsyncMock,
+ return_value=False,
+ )
+
+ response = client.post(
+ "/sessions/sess-1/messages/pending",
+ json={"message": "follow-up"},
+ )
+
+ assert response.status_code == 404
+ active_check.assert_awaited_once_with(test_user_id, "expert-archived")
+
+
+def test_queue_pending_message_skips_the_expert_gate_for_a_non_expert_session(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ mock_session = _mock_stream_queue_internals(mocker)
+ assert mock_session is not None
+ mock_session.expert_id = None
+ active_check = mocker.patch(
+ "backend.api.features.chat.routes.experts_db.owns_active_expert",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+
+ response = client.post(
+ "/sessions/sess-1/messages/pending",
+ json={"message": "follow-up"},
+ )
+
+ assert response.status_code == 200
+ active_check.assert_not_awaited()
+
+
def test_queue_pending_message_without_active_turn_returns_409(
mocker: pytest_mock.MockerFixture,
) -> None:
@@ -3221,6 +3350,35 @@ def test_get_session_returns_backward_paginated(
assert "newest_sequence" not in data
+def test_get_session_serves_history_for_an_archived_expert_session(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """Firing an expert must not take the thread's history with it.
+
+ The write gate lives on the two POST routes only. Reading a session
+ whose expert is fired stays a 200 and must not even consult the gate,
+ otherwise the read-only archive UX has nothing left to render.
+ """
+ page, _ = _make_paginated_messages(mocker)
+ page.session.expert_id = "expert-archived"
+ mocker.patch(
+ "backend.api.features.chat.routes.stream_registry.get_active_session",
+ new_callable=AsyncMock,
+ return_value=(None, None),
+ )
+ owns_active_expert = mocker.patch(
+ "backend.api.features.chat.routes.experts_db.owns_active_expert",
+ new_callable=AsyncMock,
+ return_value=False,
+ )
+
+ response = client.get("/sessions/sess-1")
+
+ assert response.status_code == 200
+ assert response.json()["messages"][0]["content"] == "hello"
+ owns_active_expert.assert_not_awaited()
+
+
def test_get_session_releases_orphan_when_redis_empty_and_db_running(
mocker: pytest_mock.MockerFixture,
) -> None:
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
index ca3f5121cd..0ac1cd09d9 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -1,3 +1,4 @@
+import asyncio
import logging
import prisma.errors
@@ -8,6 +9,7 @@ from backend.api.features.experts import scheduling
from backend.api.features.experts.models import (
PROTECTED_SOUL_RULES,
Expert,
+ ExpertIdentity,
ExpertSoulFieldsPatch,
ExpertSoulUpdate,
ExpertWorkflowRef,
@@ -16,6 +18,7 @@ from backend.api.features.experts.models import (
)
from backend.api.features.library import db as library_db
from backend.data.db import prisma as db_client
+from backend.data.db import query_raw_with_schema
from backend.data.expert_attribution import (
resolve_attributable_expert as resolve_attributable_expert_row,
)
@@ -121,6 +124,35 @@ async def list_templates() -> list[Expert]:
return [_to_model(row) for row in rows]
+# Ceiling on in-flight Redis reads inside ``_weekly_spends``. The roster is
+# user-controlled and unbounded, so an uncapped ``gather`` would ask the shared
+# Redis pool for one connection per hired expert on every team-page load.
+_WEEKLY_SPEND_READ_CONCURRENCY = 10
+
+
+async def _weekly_spends(expert_ids: list[str]) -> dict[str, int]:
+ """Weekly spend per expert, one Redis read each, run concurrently.
+
+ A read that fails degrades that expert to 0 rather than failing the whole
+ roster: the team page still renders, just without that spend figure.
+ """
+ semaphore = asyncio.Semaphore(_WEEKLY_SPEND_READ_CONCURRENCY)
+
+ async def read(expert_id: str) -> tuple[str, int]:
+ async with semaphore:
+ try:
+ return expert_id, await get_weekly_spend(expert_id)
+ except Exception:
+ logger.warning(
+ "Failed to read weekly spend for expert #%s",
+ expert_id,
+ exc_info=True,
+ )
+ return expert_id, 0
+
+ return dict(await asyncio.gather(*(read(expert_id) for expert_id in expert_ids)))
+
+
async def list_experts(user_id: str) -> list[Expert]:
rows = await prisma.models.Expert.prisma().find_many(
where={
@@ -131,12 +163,56 @@ async def list_experts(user_id: str) -> list[Expert]:
include=_WORKFLOW_INCLUDE,
)
latest_runs = await _latest_runs([row.id for row in rows])
+ weekly_spends = await _weekly_spends([row.id for row in rows])
return [
- _to_model(row, latest_runs.get(row.id), await get_weekly_spend(row.id))
+ _to_model(row, latest_runs.get(row.id), weekly_spends.get(row.id, 0))
for row in rows
]
+async def list_expert_identities(user_id: str) -> list[ExpertIdentity]:
+ """Return the lifetime roster without hydrating team-page details.
+
+ Raw SQL rather than a Prisma projection: ``find_many`` has no partial
+ ``select`` in prisma-client-py, so the ORM path would hydrate every Expert
+ column (including the Soul text this endpoint exists to avoid) on every
+ copilot mount. Only ``{schema_prefix}`` is interpolated — a server-side
+ constant from settings, never request data — and ``user_id`` is bound as
+ ``$1``. ``experts_db_test.py`` asserts the selected columns so a
+ ``schema.prisma`` rename fails in CI instead of at runtime.
+ """
+ return await query_raw_with_schema(
+ """
+ SELECT "id", "name", "avatarUrl" AS "avatar_url", "role",
+ "isArchived" AS "is_archived"
+ FROM {schema_prefix}"Expert"
+ WHERE "ownerUserId" = $1 AND "isTemplate" = false
+ """,
+ user_id,
+ model=ExpertIdentity,
+ )
+
+
+async def owns_active_expert(user_id: str, expert_id: str) -> bool:
+ """True iff *user_id* owns *expert_id* and that expert is still hireable.
+
+ The ownership half is the point: callers use this to authorise writes, so
+ a fired (archived), template, or someone else's expert must all answer
+ False here rather than being distinguished by the caller.
+ """
+ return (
+ await prisma.models.Expert.prisma().count(
+ where={
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ }
+ )
+ > 0
+ )
+
+
async def get_expert(
user_id: str, expert_id: str, *, include_workflows: bool = True
) -> Expert | None:
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
index 8320500614..e10e1ccfda 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
@@ -1,5 +1,7 @@
import asyncio
+import re
import uuid
+from pathlib import Path
from test import load_store_agents as store_assets
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -261,6 +263,167 @@ async def test_rehire_after_archive_revives_expert(server: SpinTestServer, test_
}
[email protected](loop_scope="session")
+async def test_list_expert_identities_is_lightweight_and_includes_archived(
+ server: SpinTestServer, test_user, other_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ active_template = await _seed_template(name="Max", preload_listings=[])
+ active_hired = await experts_db.hire_expert(test_user.id, active_template.id, None)
+ other_hired = await experts_db.hire_expert(other_user.id, template.id, None)
+ await experts_db.archive_expert(test_user.id, hired.expert.id)
+
+ with (
+ patch.object(experts_db, "_latest_runs", new_callable=AsyncMock) as latest_runs,
+ patch.object(
+ experts_db, "_weekly_spends", new_callable=AsyncMock
+ ) as weekly_spend,
+ ):
+ identities = await experts_db.list_expert_identities(test_user.id)
+
+ identity_ids = {item.id for item in identities}
+ identity = next(item for item in identities if item.id == hired.expert.id)
+ assert identity.name == hired.expert.name
+ assert identity.is_archived is True
+ active_identity = next(
+ item for item in identities if item.id == active_hired.expert.id
+ )
+ assert active_identity.is_archived is False
+ assert template.id not in identity_ids
+ assert active_template.id not in identity_ids
+ assert other_hired.expert.id not in identity_ids
+ latest_runs.assert_not_awaited()
+ weekly_spend.assert_not_awaited()
+
+
[email protected](loop_scope="session")
+async def test_list_experts_reads_weekly_spend_for_each_expert(
+ server: SpinTestServer, test_user
+):
+ hired = [
+ await experts_db.hire_expert(
+ test_user.id,
+ (await _seed_template(name=f"Expert{i}", preload_listings=[])).id,
+ None,
+ )
+ for i in range(3)
+ ]
+ spends = {h.expert.id: (i + 1) * 100 for i, h in enumerate(hired)}
+
+ with patch.object(
+ experts_db,
+ "_weekly_spends",
+ new=AsyncMock(return_value=spends),
+ ):
+ experts = await experts_db.list_experts(test_user.id)
+
+ assert {e.id: e.weekly_spend for e in experts if e.id in spends} == spends
+
+
[email protected](loop_scope="session")
+async def test_list_experts_defaults_a_missing_spend_entry_to_zero(
+ server: SpinTestServer, test_user
+):
+ """A spend read that degraded to a missing key must not break the roster."""
+ hired = [
+ await experts_db.hire_expert(
+ test_user.id,
+ (await _seed_template(name=f"Gap{i}", preload_listings=[])).id,
+ None,
+ )
+ for i in range(2)
+ ]
+ present, missing = hired[0].expert.id, hired[1].expert.id
+
+ with patch.object(
+ experts_db,
+ "_weekly_spends",
+ new=AsyncMock(return_value={present: 700}),
+ ):
+ experts = await experts_db.list_experts(test_user.id)
+
+ by_id = {e.id: e.weekly_spend for e in experts}
+ assert by_id[present] == 700
+ assert by_id[missing] == 0
+
+
+def test_expert_identity_projection_columns_exist_in_schema():
+ """Guard the hand-written projection in ``list_expert_identities``.
+
+ The raw SQL aliases physical column names, so a ``schema.prisma`` rename
+ would otherwise only surface as a runtime query error.
+ """
+ schema = (Path(__file__).parents[4] / "schema.prisma").read_text()
+ model = re.search(r"^model Expert \{(.*?)^\}", schema, re.S | re.M)
+ assert model is not None, "Expert model not found in schema.prisma"
+ fields = set(re.findall(r"^\s{2}(\w+)", model.group(1), re.M))
+ assert {"id", "name", "avatarUrl", "role", "isArchived"} <= fields
+ assert {"ownerUserId", "isTemplate"} <= fields
+
+
+async def test_weekly_spends_degrades_an_unexpected_read_failure_to_zero():
+ async def read(expert_id: str) -> int:
+ if expert_id == "expert-bad":
+ raise RuntimeError("redis read failed")
+ return 125
+
+ with patch.object(experts_db, "get_weekly_spend", side_effect=read):
+ spends = await experts_db._weekly_spends(["expert-ok", "expert-bad"])
+
+ assert spends == {"expert-ok": 125, "expert-bad": 0}
+
+
+async def test_weekly_spends_limits_concurrent_reads():
+ active_reads = 0
+ peak_reads = 0
+
+ async def read(_: str) -> int:
+ nonlocal active_reads, peak_reads
+ active_reads += 1
+ peak_reads = max(peak_reads, active_reads)
+ await asyncio.sleep(0)
+ active_reads -= 1
+ return 125
+
+ expert_ids = [f"expert-{index}" for index in range(25)]
+ with patch.object(experts_db, "get_weekly_spend", side_effect=read):
+ spends = await experts_db._weekly_spends(expert_ids)
+
+ assert peak_reads == experts_db._WEEKLY_SPEND_READ_CONCURRENCY
+ assert spends == {expert_id: 125 for expert_id in expert_ids}
+
+
[email protected](loop_scope="session")
+async def test_owns_active_expert_scopes_owner_and_archive_state(
+ server: SpinTestServer, test_user, other_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ assert await experts_db.owns_active_expert(test_user.id, hired.expert.id)
+ assert not await experts_db.owns_active_expert(test_user.id, template.id)
+ assert not await experts_db.owns_active_expert(other_user.id, hired.expert.id)
+
+ await experts_db.archive_expert(test_user.id, hired.expert.id)
+ assert not await experts_db.owns_active_expert(test_user.id, hired.expert.id)
+
+
[email protected](loop_scope="session")
+async def test_archive_expert_rejects_cross_user(
+ server: SpinTestServer, test_user, other_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ with pytest.raises(experts_db.ExpertNotFoundError):
+ await experts_db.archive_expert(other_user.id, hired.expert.id)
+
+ assert await experts_db.owns_active_expert(test_user.id, hired.expert.id)
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_install_workflow_on_archived_expert_raises(
server: SpinTestServer, test_user
@@ -608,7 +771,7 @@ async def test_archive_pauses_detaches_and_revive_reattaches(
server: SpinTestServer, test_user
):
"""Archiving must leave no orphaned firing: presets deactivate, schedules
- delete, and the pause is logged. Re-hiring reverses all of it."""
+ pause, and the pause is logged. Re-hiring reverses all of it."""
slv_id = await _seed_store_listing(server)
template = await _seed_template(
name="Frankie",
@@ -617,7 +780,8 @@ async def test_archive_pauses_detaches_and_revive_reattaches(
)
sched = AsyncMock()
sched.add_execution_schedule = AsyncMock(return_value=SimpleNamespace(id="sched-1"))
- sched.delete_schedule = AsyncMock()
+ sched.pause_schedule = AsyncMock()
+ sched.resume_schedule = AsyncMock()
with patch.object(scheduling, "get_scheduler_client", return_value=sched):
hired = await experts_db.hire_expert(test_user.id, template.id, None)
@@ -661,7 +825,7 @@ async def test_archive_pauses_detaches_and_revive_reattaches(
# Keyword args matter: passed positionally, user_id binds to graph_id
# and the filter silently matches nothing.
sched.get_execution_schedules.assert_awaited_with(
- user_id=test_user.id, kind="graph"
+ user_id=test_user.id, kind="graph", include_paused=False
)
preset_row = await prisma.models.AgentPreset.prisma().find_unique(
where={"id": preset.id}
@@ -681,15 +845,23 @@ async def test_archive_pauses_detaches_and_revive_reattaches(
where={"expertId": expert_id}
)
assert any(e.clearedAt is None for e in events)
- sched.delete_schedule.assert_awaited_once_with("sched-1", user_id=test_user.id)
+ sched.pause_schedule.assert_awaited_once_with("sched-1", user_id=test_user.id)
+ # Paused, not deleted: the pointer survives so the same job is resumed
+ # rather than a second one being created alongside it.
wf_row = await prisma.models.ExpertWorkflow.prisma().find_first(
where={"expertId": expert_id}
)
- assert wf_row is not None and wf_row.scheduleId is None
+ assert wf_row is not None and wf_row.scheduleId == "sched-1"
with patch.object(scheduling, "get_scheduler_client", return_value=sched):
revived = await experts_db.hire_expert(test_user.id, template.id, None)
+ sched.resume_schedule.assert_awaited_once_with("sched-1", user_id=test_user.id)
+ # Resume has to look through the paused jobs; the default read hides them.
+ sched.get_execution_schedules.assert_awaited_with(
+ user_id=test_user.id, kind="graph", include_paused=True
+ )
+ sched.add_execution_schedule.assert_awaited_once()
assert revived.expert.schedules_paused_at is None
preset_row = await prisma.models.AgentPreset.prisma().find_unique(
where={"id": preset.id}
@@ -708,12 +880,12 @@ async def test_archive_pauses_detaches_and_revive_reattaches(
@pytest.mark.asyncio(loop_scope="session")
-async def test_detach_keeps_pointer_when_schedule_delete_fails(
+async def test_detach_survives_a_schedule_that_cannot_pause(
server: SpinTestServer, test_user
):
- """A schedule that can't be deleted keeps its scheduleId pointer:
- wiping it would make re-hire create a second schedule while the
- orphaned original keeps firing."""
+ """A schedule the scheduler refuses to pause must not abort the archive:
+ the remaining schedules still pause and the run-time gate stops the
+ survivor from actually executing."""
slv_id = await _seed_store_listing(server)
template = await _seed_template(
name="Frankie",
@@ -722,26 +894,76 @@ async def test_detach_keeps_pointer_when_schedule_delete_fails(
)
sched = AsyncMock()
sched.add_execution_schedule = AsyncMock(return_value=SimpleNamespace(id="sched-1"))
- sched.delete_schedule = AsyncMock(side_effect=RuntimeError("scheduler down"))
+ sched.pause_schedule = AsyncMock(side_effect=[RuntimeError("scheduler down"), None])
with patch.object(scheduling, "get_scheduler_client", return_value=sched):
hired = await experts_db.hire_expert(test_user.id, template.id, None)
expert_id = hired.expert.id
sched.get_execution_schedules = AsyncMock(
return_value=[
+ SimpleNamespace(
+ kind="graph", id="sched-stuck", name="n", expert_id=expert_id
+ ),
SimpleNamespace(
kind="graph", id="sched-1", name="n", expert_id=expert_id
- )
+ ),
]
)
await scheduling.detach_expert_triggers(test_user.id, expert_id)
+ assert [c.args[0] for c in sched.pause_schedule.await_args_list] == [
+ "sched-stuck",
+ "sched-1",
+ ]
wf_row = await prisma.models.ExpertWorkflow.prisma().find_first(
where={"expertId": expert_id}
)
assert wf_row is not None and wf_row.scheduleId == "sched-1"
[email protected](loop_scope="session")
+async def test_user_created_schedule_survives_fire_and_rehire(
+ server: SpinTestServer, test_user
+):
+ """The schedule a user set up themselves has no ExpertWorkflow cadence
+ backing it, so it is unrecoverable if archiving deletes it. Firing must
+ pause it by expert attribution alone and re-hiring must bring back that
+ same job — inputs and all — not a reconstruction."""
+ slv_id = await _seed_store_listing(server)
+ template = await _seed_template(name="Frankie", preload_listings=[slv_id])
+ sched = AsyncMock()
+ sched.pause_schedule = AsyncMock()
+ sched.resume_schedule = AsyncMock()
+
+ with patch.object(scheduling, "get_scheduler_client", return_value=sched):
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ expert_id = hired.expert.id
+ # No preload cron, so nothing was scheduled at hire time and no
+ # ExpertWorkflow row carries a cadence to rebuild from.
+ sched.add_execution_schedule.assert_not_awaited()
+ wf_row = await prisma.models.ExpertWorkflow.prisma().find_first(
+ where={"expertId": expert_id}
+ )
+ assert wf_row is not None and wf_row.scheduleCron is None
+
+ # The user then creates their own schedule through the scheduling
+ # UI or chat; it carries expert attribution but nothing else.
+ user_schedule = SimpleNamespace(
+ kind="graph", id="user-sched", name="Weekly report", expert_id=expert_id
+ )
+ sched.get_execution_schedules = AsyncMock(return_value=[user_schedule])
+
+ await experts_db.archive_expert(test_user.id, expert_id)
+ revived = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ sched.pause_schedule.assert_awaited_once_with("user-sched", user_id=test_user.id)
+ sched.resume_schedule.assert_awaited_once_with("user-sched", user_id=test_user.id)
+ # Restored by resuming the original job, never by creating a new one.
+ sched.add_execution_schedule.assert_not_awaited()
+ assert revived.expert.is_archived is False
+ assert revived.expert.schedules_paused_at is None
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_enforce_budget_pauses_blocks_and_resumes(
server: SpinTestServer, test_user
diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.py
index 1650e68d92..d000e39e59 100644
--- a/autogpt_platform/backend/backend/api/features/experts/models.py
+++ b/autogpt_platform/backend/backend/api/features/experts/models.py
@@ -45,6 +45,14 @@ class ExpertWorkflowRef(BaseModel):
schedule_id: str | None = None
+class ExpertIdentity(BaseModel):
+ id: str
+ name: str
+ avatar_url: str | None
+ role: str
+ is_archived: bool
+
+
class Expert(BaseModel):
id: str
name: str
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes.py b/autogpt_platform/backend/backend/api/features/experts/routes.py
index aa3e8769fa..ac7c24e771 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routes.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routes.py
@@ -7,6 +7,7 @@ from backend.api.features.experts import experts_db, scheduling
from backend.api.features.experts.models import (
Expert,
ExpertDetachPreview,
+ ExpertIdentity,
ExpertSoulUpdate,
ExpertWorkflowRef,
HireResult,
@@ -52,9 +53,18 @@ async def hire_expert(
async def list_experts(
user_id: str = Security(autogpt_auth_lib.get_user_id),
) -> list[Expert]:
+ """List the user's active hired experts."""
return await experts_db.list_experts(user_id)
[email protected]("/identities", operation_id="list_expert_identities")
+async def list_expert_identities(
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> list[ExpertIdentity]:
+ """List the lightweight active and archived identity projection for chat."""
+ return await experts_db.list_expert_identities(user_id)
+
+
@router.get(
"/{expert_id}",
operation_id="get_expert",
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes_test.py b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
index 879924ba74..179f8e3ed0 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
@@ -20,6 +20,7 @@ from backend.api.features.experts import experts_db
from backend.api.features.experts.models import (
PROTECTED_SOUL_RULES,
Expert,
+ ExpertIdentity,
ExpertSoulUpdate,
ExpertWorkflowRef,
HireResult,
@@ -202,6 +203,40 @@ def test_get_expert_returns_expert(
mock_get.assert_awaited_once_with(test_user_id, "expert-1")
+def test_list_expert_identities_returns_lifetime_roster_projection(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ identities = [
+ ExpertIdentity(
+ id="expert-1",
+ name="Maria",
+ avatar_url=None,
+ role="Marketing Specialist",
+ is_archived=True,
+ )
+ ]
+ mock_list = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.list_expert_identities",
+ new_callable=AsyncMock,
+ return_value=identities,
+ )
+
+ response = client.get("/experts/identities")
+
+ assert response.status_code == 200
+ assert response.json() == [
+ {
+ "id": "expert-1",
+ "name": "Maria",
+ "avatar_url": None,
+ "role": "Marketing Specialist",
+ "is_archived": True,
+ }
+ ]
+ mock_list.assert_awaited_once_with(test_user_id)
+
+
# ─── Soul ──────────────────────────────────────────────────────────────
diff --git a/autogpt_platform/backend/backend/api/features/experts/scheduling.py b/autogpt_platform/backend/backend/api/features/experts/scheduling.py
index 2689beb349..ebbde5371c 100644
--- a/autogpt_platform/backend/backend/api/features/experts/scheduling.py
+++ b/autogpt_platform/backend/backend/api/features/experts/scheduling.py
@@ -16,11 +16,9 @@ import prisma.models
from backend.api.features.experts.models import ExpertDetachPreview
from backend.copilot import db as chat_db
from backend.data.expert_spend import get_weekly_spend, reset_weekly_spend
-from backend.data.user import get_user_by_id
from backend.util.clients import get_scheduler_client
from backend.util.exceptions import ExpertRunPausedError
from backend.util.settings import Settings
-from backend.util.timezone_utils import get_user_timezone_or_utc
logger = logging.getLogger(__name__)
settings = Settings()
@@ -109,7 +107,7 @@ async def _delete_schedule_best_effort(
"""Never leave a schedule firing with no row pointing at it. One
immediate retry covers transient RPC blips; a persistent failure is
logged loudly by id. A surviving orphan is not invisible: it stays
- expert-attributed, so it shows up in the detach preview and is deleted
+ expert-attributed, so it shows up in the detach preview and is paused
by the archive detach sweep."""
last_error: Exception | None = None
for _attempt in range(2):
@@ -124,9 +122,11 @@ async def _delete_schedule_best_effort(
)
-async def _get_expert_schedules(user_id: str, expert_id: str) -> list:
+async def _get_expert_schedules(
+ user_id: str, expert_id: str, *, include_paused: bool = False
+) -> list:
schedules = await get_scheduler_client().get_execution_schedules(
- user_id=user_id, kind="graph"
+ user_id=user_id, kind="graph", include_paused=include_paused
)
return [s for s in schedules if s.kind == "graph" and s.expert_id == expert_id]
@@ -150,11 +150,19 @@ async def get_detach_preview(user_id: str, expert_id: str) -> ExpertDetachPrevie
async def detach_expert_triggers(user_id: str, expert_id: str) -> None:
- """Deactivate the expert's presets and delete her schedules.
+ """Deactivate the expert's presets and pause her schedules.
Called on archive. Preset deactivation is the loud guard against
orphaned webhook firing; the run-time gate (``enforce_expert_run_budget``
refusing archived/paused experts) is the backstop for anything missed.
+
+ Schedules are paused, never deleted. Pausing keeps the trigger, inputs
+ and credentials on the job, so ``reattach_expert_triggers`` can restore
+ the exact schedule on re-hire — and it treats every schedule the same
+ whether the roster template seeded it or the user created it themselves
+ through the scheduling UI or chat. Deleting used to lose the latter set
+ permanently, because only template-seeded cadences are recoverable from
+ ``ExpertWorkflow.scheduleCron``.
"""
# Only presets this flow turns off are marked, so re-hire restores
# exactly them — one the user had deliberately disabled before archiving
@@ -169,31 +177,29 @@ async def detach_expert_triggers(user_id: str, expert_id: str) -> None:
data={"isActive": False, "deactivatedByExpertArchive": True},
)
scheduler = get_scheduler_client()
- deleted_ids: list[str] = []
for schedule in await _get_expert_schedules(user_id, expert_id):
try:
- await scheduler.delete_schedule(schedule.id, user_id=user_id)
- deleted_ids.append(schedule.id)
+ await scheduler.pause_schedule(schedule.id, user_id=user_id)
except Exception as e:
+ # A schedule that refuses to pause keeps firing, so the run-time
+ # gate is what actually stops it. Log by id so the survivor is
+ # findable; it stays expert-attributed and a later detach retries.
logger.warning(
- f"Failed to delete schedule #{schedule.id} while detaching "
+ f"Failed to pause schedule #{schedule.id} while detaching "
f"expert #{expert_id}: {type(e).__name__}: {e}"
)
- # Only pointers to schedules that are actually gone are cleared. A
- # failed deletion keeps its scheduleId, so the job stays visible and a
- # later detach can retry it — wiping it would make re-hire create a
- # second schedule while the orphaned original keeps firing.
- if deleted_ids:
- await prisma.models.ExpertWorkflow.prisma().update_many(
- where={"expertId": expert_id, "scheduleId": {"in": deleted_ids}},
- data={"scheduleId": None},
- )
async def reattach_expert_triggers(user_id: str, expert_id: str) -> None:
"""Reverse of ``detach_expert_triggers``, for re-hire revival:
reactivate the presets archiving deactivated (never ones the user had
- turned off themselves) and recreate schedules from the stored cadence."""
+ turned off themselves) and resume the schedules archiving paused.
+
+ Resume is by expert attribution, the same key the pause used, so every
+ schedule comes back regardless of who created it. APScheduler recomputes
+ the next fire from the trigger, so a long-archived expert resumes at her
+ next cadence rather than replaying every run she missed.
+ """
await prisma.models.AgentPreset.prisma().update_many(
where={
"expertId": expert_id,
@@ -203,33 +209,17 @@ async def reattach_expert_triggers(user_id: str, expert_id: str) -> None:
},
data={"isActive": True, "deactivatedByExpertArchive": False},
)
- workflows = await prisma.models.ExpertWorkflow.prisma().find_many(
- where={
- "expertId": expert_id,
- "scheduleCron": {"not": None},
- "scheduleId": None,
- },
- include={"LibraryAgent": True, "StoreListingVersion": True},
- )
- if not workflows:
- return
- user = await get_user_by_id(user_id)
- user_timezone = get_user_timezone_or_utc(user.timezone if user else None)
- for workflow in workflows:
- agent = workflow.LibraryAgent
- if agent is None or not workflow.scheduleCron:
- continue
- listing = workflow.StoreListingVersion
- await create_workflow_schedule(
- workflow_row_id=workflow.id,
- expert_id=expert_id,
- user_id=user_id,
- cron=workflow.scheduleCron,
- graph_id=agent.agentGraphId,
- graph_version=agent.agentGraphVersion,
- name=listing.name if listing else "Expert workflow",
- user_timezone=user_timezone,
- )
+ scheduler = get_scheduler_client()
+ for schedule in await _get_expert_schedules(
+ user_id, expert_id, include_paused=True
+ ):
+ try:
+ await scheduler.resume_schedule(schedule.id, user_id=user_id)
+ except Exception as e:
+ logger.warning(
+ f"Failed to resume schedule #{schedule.id} while reviving "
+ f"expert #{expert_id}: {type(e).__name__}: {e}"
+ )
async def pause_expert_schedules(user_id: str, expert_id: str, reason: str) -> bool:
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index 5c7340487b..a87f5fecec 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -1872,32 +1872,73 @@ class Scheduler(AppService):
``SchedulerClient.delete_schedule`` and accepts both graph and
copilot-turn schedules.
"""
+ job, info = self._authorized_job(schedule_id, user_id, action="delete")
+ logger.info(f"Deleting job {schedule_id} (kind={info.kind})")
+ job.remove()
+ # Invalidate the read cache so the deletion shows up immediately
+ # on the next ``get_execution_schedules`` call.
+ self._invalidate_jobs_cache()
+ return info
+
+ def _authorized_job(
+ self, schedule_id: str, user_id: str, *, action: str
+ ) -> tuple[JobObj, Union[GraphExecutionJobInfo, CopilotTurnJobInfo]]:
+ """Load a schedule and check *user_id* owns it.
+
+ Shared by delete/pause/resume so all three authorize identically:
+ kwargs that parse as neither kind carry no `user_id` field to
+ authorize against, so acting on them would let any caller who can
+ guess a schedule_id mutate corrupted rows. Surface 404 rather than
+ a distinct error so the shape can't be probed by timing either.
+ """
job = self.scheduler.get_job(schedule_id, jobstore=Jobstores.EXECUTION.value)
if not job:
raise NotFoundError(f"Job #{schedule_id} not found.")
-
info = _job_to_info(job)
if info is None:
- # kwargs parse as neither graph nor copilot-turn — we have no
- # `user_id` field to authorize against, so refuse the delete.
- # Removing without an ownership check would let any caller who
- # can guess a schedule_id wipe corrupted rows. Surface 404 so
- # the caller can't probe for shape via timing either.
logger.warning(
- f"Refusing delete for job {schedule_id} with unrecognized "
+ f"Refusing {action} for job {schedule_id} with unrecognized "
f"kwargs shape (no parseable user_id to authorize against)"
)
raise NotFoundError(f"Job #{schedule_id} has invalid schedule data.")
-
if info.user_id != user_id:
raise NotAuthorizedError("User ID does not match the job's user ID")
+ return job, info
- logger.info(f"Deleting job {schedule_id} (kind={info.kind})")
- job.remove()
- # Invalidate the read cache so the deletion shows up immediately
- # on the next ``get_execution_schedules`` call.
+ @expose
+ def pause_execution_schedule(self, schedule_id: str, user_id: str) -> bool:
+ """Suspend a schedule without discarding it.
+
+ APScheduler persists a pause as ``next_run_time = NULL``, which
+ ``get_execution_schedules`` already skips — so a paused schedule
+ disappears from every read path while keeping its trigger, inputs
+ and credentials intact for ``resume_execution_schedule``. Returns
+ False when it was already paused, so callers don't double-log.
+ """
+ job, info = self._authorized_job(schedule_id, user_id, action="pause")
+ if job.next_run_time is None:
+ return False
+ logger.info(f"Pausing job {schedule_id} (kind={info.kind})")
+ self.scheduler.pause_job(schedule_id, jobstore=Jobstores.EXECUTION.value)
self._invalidate_jobs_cache()
- return info
+ return True
+
+ @expose
+ def resume_execution_schedule(self, schedule_id: str, user_id: str) -> bool:
+ """Reverse of ``pause_execution_schedule``.
+
+ APScheduler recomputes ``next_run_time`` from the trigger, so fires
+ missed while paused are NOT backfilled — a re-hired expert picks up
+ at her next cadence instead of replaying the whole archived window.
+ Returns False when the schedule was not paused.
+ """
+ job, info = self._authorized_job(schedule_id, user_id, action="resume")
+ if job.next_run_time is not None:
+ return False
+ logger.info(f"Resuming job {schedule_id} (kind={info.kind})")
+ self.scheduler.resume_job(schedule_id, jobstore=Jobstores.EXECUTION.value)
+ self._invalidate_jobs_cache()
+ return True
@expose
def get_graph_execution_schedules(
@@ -1986,6 +2027,7 @@ class Scheduler(AppService):
kind: str | None = None,
organization_id: str | None = None,
team_ids: list[str] | None = None,
+ include_paused: bool = False,
) -> list[Union[GraphExecutionJobInfo, CopilotTurnJobInfo]]:
"""Return schedules of both kinds, filtered by the given fields.
@@ -1997,11 +2039,20 @@ class Scheduler(AppService):
the org/team visibility rules apply instead of strict ownership:
own schedules + org-home schedules + schedules of teams in
*team_ids* (resolved by the caller, who has async DB access).
+
+ Paused jobs (``next_run_time is None``) are hidden by default, which
+ is what keeps a fired expert's suspended schedules out of every user
+ -facing listing. *include_paused* is for the lifecycle callers that
+ have to find them again to resume them. Fired one-shot jobs share
+ the same null marker, so they resurface too — filter by kind/id if
+ that matters to the caller.
"""
jobs: list[JobObj] = self._get_jobs_cached()
results: list[Union[GraphExecutionJobInfo, CopilotTurnJobInfo]] = []
for job in jobs:
- info = _job_to_info(job) if job.next_run_time is not None else None
+ if job.next_run_time is None and not include_paused:
+ continue
+ info = _job_to_info(job)
if info is None:
continue
if kind is not None and info.kind != kind:
@@ -2425,6 +2476,8 @@ class SchedulerClient(AppServiceClient):
add_execution_schedule = endpoint_to_async(Scheduler.add_graph_execution_schedule)
add_copilot_turn_schedule = endpoint_to_async(Scheduler.add_copilot_turn_schedule)
delete_schedule = endpoint_to_async(Scheduler.delete_graph_execution_schedule)
+ pause_schedule = endpoint_to_async(Scheduler.pause_execution_schedule)
+ resume_schedule = endpoint_to_async(Scheduler.resume_execution_schedule)
# Graph-only typed list — for legacy callers that need GraphExecutionJobInfo.
get_graph_execution_schedules = endpoint_to_async(
Scheduler.get_graph_execution_schedules
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx
index cd58e950b1..d5a414993c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx
@@ -47,6 +47,7 @@ export function CopilotChatHost({
sessionDryRun,
sessionChatStatus,
expertIdentity,
+ isResolvingExpertIdentity,
isAdoptingExpertSession,
isKickoffStarting,
} = useCopilotPage();
@@ -90,6 +91,7 @@ export function CopilotChatHost({
onDroppedFilesConsumed={onDroppedFilesConsumed}
turnStats={turnStats}
expertIdentity={expertIdentity}
+ isResolvingExpertIdentity={isResolvingExpertIdentity}
isAdoptingExpertSession={isAdoptingExpertSession}
isKickoffStarting={isKickoffStarting}
/>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx
index ce965ce4d8..ac8ab8782e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx
@@ -125,13 +125,14 @@ describe("AutoPilot streaming — error paths", () => {
const expertId = "3f8b0f7e-9f30-4a3b-a6a1-000000000001";
flagState.experts = true;
server.use(
- http.get("*/api/experts", () =>
+ http.get("*/api/experts/identities", () =>
HttpResponse.json([
{
id: expertId,
name: "Maria",
avatar_url: null,
role: "Operations expert",
+ is_archived: false,
},
]),
),
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsx
index 287c1d974c..7ddd022ff3 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsx
@@ -460,4 +460,36 @@ describe("useExpertKickoff", () => {
expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("pending");
expect(screen.getByTestId("kickoff-starting").textContent).toBe("true");
});
+
+ // `useCopilotPage` hands this hook `expertId: null` whenever the roster
+ // refuses the id in the URL (fired, bogus, or unreadable) while `kickoff=1`
+ // is still in the query string. Every path here has to stay inert on that
+ // pair rather than reach storage or the network with a null id.
+ it("stays inert when kickoff is armed without a resolvable expert", async () => {
+ let listCount = 0;
+ let createCount = 0;
+ server.use(
+ stubTransports(),
+ http.get("*/api/chat/sessions", () => {
+ listCount += 1;
+ return HttpResponse.json({ sessions: [], total: 0 });
+ }),
+ http.post("*/api/chat/sessions", () => {
+ createCount += 1;
+ return HttpResponse.json({ id: "should-not-happen" });
+ }),
+ );
+
+ renderKickoff("?kickoff=1");
+
+ await waitFor(() =>
+ expect(screen.getByTestId("kickoff-starting").textContent).toBe("false"),
+ );
+ expect(sendSpy).not.toHaveBeenCalled();
+ expect(listCount).toBe(0);
+ expect(createCount).toBe(0);
+ expect(screen.getByTestId("session-id").textContent).toBe("none");
+ expect(screen.getByTestId("settled-count").textContent).toBe("0");
+ expect(window.localStorage.length).toBe(0);
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-send-guard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-send-guard.test.tsx
new file mode 100644
index 0000000000..b6bdceb600
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-send-guard.test.tsx
@@ -0,0 +1,184 @@
+import { renderHook, waitFor } from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// The guard under test is `if (isExpertSendLocked) return;` inside
+// useCopilotPage.onSend — the LAST line of defence, behind ChatContainer's
+// guardedOnSend wrapper. Deleting it would leave every ChatContainer test
+// green while the hook itself silently sent to a fired expert, so it needs
+// coverage that does not go through the component.
+
+const expertMapState = vi.hoisted(() => ({
+ expertsById: new Map<string, unknown>(),
+ hasExpertsSettled: true,
+ hasExpertsErrored: false,
+}));
+
+const sendNewMessage = vi.hoisted(() => vi.fn());
+const queueFollowUpMessage = vi.hoisted(() => vi.fn());
+
+vi.mock("@/services/feature-flags/use-get-flag", () => ({
+ Flag: {
+ CHAT_MODE_OPTION: "chat-mode-option",
+ HIRE_EXPERTS: "hire-experts",
+ ONBOARDING_BRAIN_DUMP: "onboarding-brain-dump",
+ },
+ useGetFlag: (flag: string) => flag === "hire-experts",
+}));
+
+vi.mock("nuqs", () => ({
+ parseAsString: {},
+ useQueryState: () => ["expert-maria", vi.fn()],
+}));
+
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({
+ user: { id: "user-1" },
+ isUserLoading: false,
+ isLoggedIn: true,
+ }),
+}));
+
+vi.mock("@/app/api/__generated__/endpoints/brain-dump/brain-dump", () => ({
+ useCompleteBrainDumpGreeting: () => ({ mutate: vi.fn() }),
+}));
+
+vi.mock("../useExpertMap", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../useExpertMap")>();
+ return { ...actual, useExpertMap: () => expertMapState };
+});
+
+vi.mock("../useChatSession", () => ({
+ useChatSession: () => ({
+ sessionId: "session-1",
+ setSessionId: vi.fn(),
+ sessionLlmAuthProvider: "platform",
+ sessionExpertId: "expert-maria",
+ isAdoptingExpertSession: false,
+ hydratedMessages: [],
+ rawSessionMessages: [],
+ historicalTurnStats: new Map(),
+ hasActiveStream: false,
+ activeStreamStartedAt: null,
+ hasMoreMessages: false,
+ oldestSequence: null,
+ isLoadingSession: false,
+ isSessionError: false,
+ createSession: vi.fn(),
+ isCreatingSession: false,
+ refetchSession: vi.fn(),
+ sessionDryRun: false,
+ sessionChatStatus: "idle",
+ }),
+}));
+
+vi.mock("../useCopilotStream", () => ({
+ useCopilotStream: () => ({
+ messages: [],
+ setMessages: vi.fn(),
+ sendMessage: vi.fn(),
+ stop: vi.fn(),
+ status: "ready",
+ error: undefined,
+ isReconnecting: false,
+ isRestoringActiveSession: false,
+ isSyncing: false,
+ isUserStoppingRef: { current: false },
+ isUserStopping: false,
+ rateLimitMessage: null,
+ dismissRateLimit: vi.fn(),
+ }),
+}));
+
+vi.mock("../useSendMessage", () => ({
+ useSendMessage: () => ({
+ onSend: sendNewMessage,
+ isUploadingFiles: false,
+ setPendingFileParts: vi.fn(),
+ }),
+}));
+
+vi.mock("../useLoadMoreMessages", () => ({
+ useLoadMoreMessages: () => ({
+ pagedMessages: [],
+ pagedTurnStats: new Map(),
+ hasMore: false,
+ isLoadingMore: false,
+ loadMore: vi.fn(),
+ }),
+}));
+
+vi.mock("../useCopilotPendingChips", () => ({
+ useCopilotPendingChips: () => ({ queuedMessages: [], queueMessage: vi.fn() }),
+}));
+
+vi.mock("../useCopilotNotifications", () => ({
+ useCopilotNotifications: () => undefined,
+}));
+vi.mock("../useSessionTitlePoll", () => ({
+ useSessionTitlePoll: () => undefined,
+}));
+vi.mock("../useWorkflowImportAutoSubmit", () => ({
+ useWorkflowImportAutoSubmit: () => undefined,
+}));
+vi.mock("../useExpertKickoff", () => ({
+ useExpertKickoff: () => ({ isKickoffStarting: false }),
+}));
+vi.mock("../helpers/queueFollowUpMessage", () => ({ queueFollowUpMessage }));
+
+import { useCopilotPage } from "../useCopilotPage";
+
+function setExpert(identity: {
+ isArchived: boolean;
+ readOnlyReason: "fired" | "unavailable" | "unknown" | null;
+}) {
+ expertMapState.expertsById = new Map([
+ [
+ "expert-maria",
+ {
+ id: "expert-maria",
+ name: "Maria",
+ avatarUrl: null,
+ role: "Marketing Strategist",
+ ...identity,
+ },
+ ],
+ ]);
+ expertMapState.hasExpertsSettled = true;
+ expertMapState.hasExpertsErrored = false;
+}
+
+afterEach(() => {
+ sendNewMessage.mockReset();
+ queueFollowUpMessage.mockReset();
+});
+
+describe("useCopilotPage — expert send guard", () => {
+ it("drops a send when the session's expert has been fired", async () => {
+ setExpert({ isArchived: true, readOnlyReason: "fired" });
+
+ const { result } = renderHook(() => useCopilotPage());
+ await result.current.onSend("are you still there?");
+
+ expect(sendNewMessage).not.toHaveBeenCalled();
+ expect(queueFollowUpMessage).not.toHaveBeenCalled();
+ });
+
+ it("drops a send while the expert identity is still unresolved", async () => {
+ setExpert({ isArchived: false, readOnlyReason: null });
+ expertMapState.hasExpertsSettled = false;
+
+ const { result } = renderHook(() => useCopilotPage());
+ await result.current.onSend("hello");
+
+ expect(sendNewMessage).not.toHaveBeenCalled();
+ });
+
+ it("still sends for an active expert", async () => {
+ setExpert({ isArchived: false, readOnlyReason: null });
+
+ const { result } = renderHook(() => useCopilotPage());
+ await result.current.onSend("hello");
+
+ await waitFor(() => expect(sendNewMessage).toHaveBeenCalledTimes(1));
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx
index bc95e1037a..9bbc5de5aa 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx
@@ -1,7 +1,7 @@
import { getGetV2ListSessionsMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";
import {
getGetExpertMockHandler,
- getListExpertsMockHandler,
+ getListExpertIdentitiesMockHandler,
} from "@/app/api/__generated__/endpoints/experts/experts.msw";
import { getGetV1ListExecutionSchedulesForAUserMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";
import type { Expert } from "@/app/api/__generated__/models/expert";
@@ -22,6 +22,7 @@ import { parseAsString, useQueryState } from "nuqs";
import { withNuqsTestingAdapter } from "nuqs/adapters/testing";
import { afterEach, describe, expect, it, vi } from "vitest";
import { RecipientChip } from "../components/ChatInput/components/RecipientChip";
+import { useRecipientPicker } from "../components/EmptySession/useRecipientPicker";
import { ChatMessagesContainer } from "../components/ChatMessagesContainer/ChatMessagesContainer";
import { ChatSidebar } from "../components/ChatSidebar/ChatSidebar";
import { useChatSession } from "../useChatSession";
@@ -353,7 +354,7 @@ describe("useChatSession — expert sessions", () => {
messages: [],
}),
),
- getListExpertsMockHandler([mariaExpert]),
+ getListExpertIdentitiesMockHandler([mariaExpert]),
);
render(
@@ -425,7 +426,7 @@ describe("ChatSidebar — expert groups", () => {
],
total: 2,
}),
- getListExpertsMockHandler([mariaExpert]),
+ getListExpertIdentitiesMockHandler([mariaExpert]),
);
render(
@@ -454,7 +455,7 @@ describe("ChatSidebar — expert groups", () => {
],
total: 2,
}),
- getListExpertsMockHandler([]),
+ getListExpertIdentitiesMockHandler([]),
);
render(
@@ -488,7 +489,7 @@ describe("ChatSidebar — expert groups", () => {
],
total: 3,
}),
- getListExpertsMockHandler([mariaExpert]),
+ getListExpertIdentitiesMockHandler([mariaExpert]),
);
render(
@@ -529,7 +530,7 @@ describe("ChatSidebar — expert groups", () => {
],
total: 8,
}),
- getListExpertsMockHandler([mariaExpert]),
+ getListExpertIdentitiesMockHandler([mariaExpert]),
);
render(
@@ -565,7 +566,7 @@ describe("ChatSidebar — expert groups", () => {
],
total: 2,
}),
- getListExpertsMockHandler([mariaExpert]),
+ getListExpertIdentitiesMockHandler([mariaExpert]),
);
render(
@@ -591,7 +592,7 @@ describe("ChatSidebar — expert groups", () => {
flagState.values = { "hire-experts": false };
let expertsRequests = 0;
server.use(
- http.get("*/api/experts", () => {
+ http.get("*/api/experts/identities", () => {
expertsRequests += 1;
return HttpResponse.json([mariaExpert]);
}),
@@ -634,6 +635,8 @@ describe("ChatMessagesContainer — expert identity", () => {
name: "Maria",
avatarUrl: mariaExpert.avatar_url,
role: mariaExpert.role,
+ isArchived: false,
+ readOnlyReason: null,
};
it("shows the expert name and avatar in the thread header only", () => {
@@ -695,6 +698,37 @@ describe("ChatMessagesContainer — expert identity", () => {
expect(await screen.findByTestId("schedule-row")).toBeDefined();
});
+ it("does not read the fired expert's detail record for the schedules button", async () => {
+ let expertDetailRequests = 0;
+ server.use(
+ http.get("*/api/experts/expert-maria", () => {
+ expertDetailRequests += 1;
+ return HttpResponse.json(
+ { detail: "Expert not found" },
+ { status: 404 },
+ );
+ }),
+ getGetV1ListExecutionSchedulesForAUserMockHandler([]),
+ );
+ render(
+ <ChatMessagesContainer
+ messages={[assistantMessage]}
+ status="ready"
+ error={undefined}
+ isLoading={false}
+ expertIdentity={{
+ ...mariaIdentity,
+ isArchived: true,
+ readOnlyReason: "fired",
+ }}
+ />,
+ );
+
+ expect(await screen.findByTestId("expert-thread-header")).toBeDefined();
+ expect(screen.queryByTestId("expert-schedules-button")).toBeNull();
+ expect(expertDetailRequests).toBe(0);
+ });
+
it("renders no expert header or identity for plain sessions", () => {
render(
<ChatMessagesContainer
@@ -710,6 +744,17 @@ describe("ChatMessagesContainer — expert identity", () => {
});
});
+function RecipientPickerHarness() {
+ const [expertId] = useQueryState("expertId", parseAsString);
+ const { recipient } = useRecipientPicker();
+ return (
+ <div>
+ <div data-testid="picker-expert-id">{expertId ?? "none"}</div>
+ <div data-testid="picker-recipient">{recipient.name}</div>
+ </div>
+ );
+}
+
describe("recipient picker", () => {
it("does not look up or adopt the expert's latest thread when the recipient is picked after mount", async () => {
let expertListRequests = 0;
@@ -796,4 +841,60 @@ describe("recipient picker", () => {
await userEvent.click(await screen.findByText("Maria"));
expect(onSelect).toHaveBeenCalledWith("expert-maria");
});
+
+ it("clears an unresolved expert recipient after the identity query errors", async () => {
+ server.use(
+ http.get("*/api/experts/identities", () =>
+ HttpResponse.json({ detail: "boom" }, { status: 500 }),
+ ),
+ );
+
+ const ErrorWrapper = withNuqsTestingAdapter({
+ searchParams: "?expertId=expert-maria",
+ hasMemory: true,
+ });
+ render(
+ <ErrorWrapper>
+ <RecipientPickerHarness />
+ </ErrorWrapper>,
+ );
+
+ await waitFor(() =>
+ expect(screen.getByTestId("picker-expert-id").textContent).toBe("none"),
+ );
+ expect(screen.getByTestId("picker-recipient").textContent).toBe(
+ "Autopilot",
+ );
+ });
+
+ it("clears an archived expert recipient after identities load", async () => {
+ server.use(
+ getListExpertIdentitiesMockHandler([
+ {
+ id: "expert-maria",
+ name: "Maria",
+ avatar_url: "https://example.com/maria.png",
+ role: "Marketing Strategist",
+ is_archived: true,
+ },
+ ]),
+ );
+
+ const ArchivedWrapper = withNuqsTestingAdapter({
+ searchParams: "?expertId=expert-maria",
+ hasMemory: true,
+ });
+ render(
+ <ArchivedWrapper>
+ <RecipientPickerHarness />
+ </ArchivedWrapper>,
+ );
+
+ await waitFor(() =>
+ expect(screen.getByTestId("picker-expert-id").textContent).toBe("none"),
+ );
+ expect(screen.getByTestId("picker-recipient").textContent).toBe(
+ "Autopilot",
+ );
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
index 6841a03e3c..d8c9a036fb 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
@@ -18,6 +18,7 @@ import { UsageLimitReachedCard } from "../UsageLimits/UsageLimitReachedCard/Usag
import { useIsUsageLimitReached } from "../UsageLimits/useIsUsageLimitReached";
import { TaskProgressBar } from "../TaskProgressBar/TaskProgressBar";
import { getLatestTaskList } from "../TaskProgressBar/helpers";
+import { ArchivedExpertNotice } from "./components/ArchivedExpertNotice";
import { SharedChatNotice } from "./components/SharedChatNotice";
import { useAutoOpenArtifacts } from "./useAutoOpenArtifacts";
import type { ExpertIdentity } from "../../useExpertMap";
@@ -74,6 +75,9 @@ export interface ChatContainerProps {
/** Expert identity for expert-scoped sessions (thread header + assistant
* avatar/name). Null = default header. */
expertIdentity?: ExpertIdentity | null;
+ /** True while an expert-scoped session's active/archived identity is still
+ * unresolved. Keep every send path locked until the roster settles. */
+ isResolvingExpertIdentity?: boolean;
/** True while a `?expertId=` deep link may still swap this view for the
* expert's latest thread — the composer stays locked so a draft can't be
* lost to that navigation. */
@@ -81,6 +85,9 @@ export interface ChatContainerProps {
/** True until a newly hired expert's first kickoff has been handed off. */
isKickoffStarting?: boolean;
}
+
+const NO_OP_SEND = () => undefined;
+
export const ChatContainer = ({
messages,
status,
@@ -108,6 +115,7 @@ export const ChatContainer = ({
onDroppedFilesConsumed,
turnStats,
expertIdentity,
+ isResolvingExpertIdentity,
isAdoptingExpertSession,
isKickoffStarting,
}: ChatContainerProps) => {
@@ -136,7 +144,21 @@ export const ChatContainer = ({
!!isReconnecting || isLoadingSession || !!isSessionError;
const isLimitReached = useIsUsageLimitReached();
const isInputDisabled =
- isSessionUnavailable || isLimitReached || !!isKickoffStarting;
+ isSessionUnavailable ||
+ isLimitReached ||
+ !!isResolvingExpertIdentity ||
+ !!isKickoffStarting;
+ // A fired (archived) expert's threads stay as read-only history — the
+ // composer is replaced by a quiet notice so no new turns can be sent.
+ const archivedExpertIdentity = expertIdentity?.isArchived
+ ? expertIdentity
+ : null;
+ const isExpertArchived = archivedExpertIdentity !== null;
+ const isSendLocked = isExpertArchived || !!isResolvingExpertIdentity;
+ // NO_OP is module-level so a locked composer keeps a stable function identity
+ // across renders — otherwise every consumer of `guardedOnSend` (the actions
+ // provider, ChatInput, EmptySession, handleRetry) re-renders on each pass.
+ const guardedOnSend = isSendLocked ? NO_OP_SEND : onSend;
const inputLayoutId = "copilot-2-chat-input";
// Measure the usage-limit overlay so the messages scroll area can pad its
@@ -161,7 +183,7 @@ export const ChatContainer = ({
return () => ro.disconnect();
}, [isLimitReached]);
- // Retry: re-send the last user message (used by ErrorCard on transient errors)
+ // Retry: re-send the last user message (used by ErrorCard on transient errors).
const handleRetry = useCallback(() => {
const lastUserMsg = [...messages].reverse().find((m) => m.role === "user");
const lastText = lastUserMsg?.parts
@@ -177,7 +199,7 @@ export const ChatContainer = ({
const kickoffAttemptToken = lastUserMsg
? getKickoffAttemptToken(lastUserMsg)
: null;
- onSend(
+ guardedOnSend(
kickoffExpertId ? stripLegacyKickoffMarker(lastText) : lastText,
undefined,
undefined,
@@ -192,10 +214,10 @@ export const ChatContainer = ({
: undefined,
);
}
- }, [messages, onSend]);
+ }, [guardedOnSend, messages]);
return (
- <CopilotChatActionsProvider onSend={onSend}>
+ <CopilotChatActionsProvider onSend={guardedOnSend}>
<LayoutGroup id="copilot-2-chat-layout">
<div className="flex h-full min-h-0 w-full flex-col px-2 lg:px-0">
{sessionId ? (
@@ -219,74 +241,81 @@ export const ChatContainer = ({
bottomContentPadding={usageCardHeight}
expertIdentity={expertIdentity}
/>
- <motion.div
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- transition={{ duration: 0.3 }}
- className="relative px-3 pb-6 pt-2"
- >
- {isLimitReached && (
- <div
- ref={usageCardRef}
- className="pointer-events-none absolute bottom-full left-0 right-0 z-20 mb-2.5 pb-2"
- >
+ {archivedExpertIdentity ? (
+ <ArchivedExpertNotice
+ expertName={archivedExpertIdentity.name}
+ reason={archivedExpertIdentity.readOnlyReason ?? "fired"}
+ />
+ ) : (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ transition={{ duration: 0.3 }}
+ className="relative px-3 pb-6 pt-2"
+ >
+ {isLimitReached && (
<div
- aria-hidden="true"
- data-testid="usage-limit-backdrop"
- className="absolute -inset-x-14 -top-20 bottom-[-18px] overflow-hidden rounded-[2rem] bg-[radial-gradient(ellipse_at_center,rgba(250,250,250,0.96)_0%,rgba(250,250,250,0.9)_42%,rgba(250,250,250,0.58)_68%,rgba(250,250,250,0)_100%)] backdrop-blur-lg [mask-image:linear-gradient(to_bottom,transparent_0%,black_26%,black_100%)]"
+ ref={usageCardRef}
+ className="pointer-events-none absolute bottom-full left-0 right-0 z-20 mb-2.5 pb-2"
>
- <div className="absolute inset-x-10 bottom-0 h-28 rounded-full bg-[#fafafa]/80 blur-2xl" />
- <div className="absolute inset-x-16 bottom-8 h-16 rounded-full bg-white/55 blur-xl" />
- </div>
- <div className="pointer-events-auto relative px-3">
- <UsageLimitReachedCard />
+ <div
+ aria-hidden="true"
+ data-testid="usage-limit-backdrop"
+ className="absolute -inset-x-14 -top-20 bottom-[-18px] overflow-hidden rounded-[2rem] bg-[radial-gradient(ellipse_at_center,rgba(250,250,250,0.96)_0%,rgba(250,250,250,0.9)_42%,rgba(250,250,250,0.58)_68%,rgba(250,250,250,0)_100%)] backdrop-blur-lg [mask-image:linear-gradient(to_bottom,transparent_0%,black_26%,black_100%)]"
+ >
+ <div className="absolute inset-x-10 bottom-0 h-28 rounded-full bg-[#fafafa]/80 blur-2xl" />
+ <div className="absolute inset-x-16 bottom-8 h-16 rounded-full bg-white/55 blur-xl" />
+ </div>
+ <div className="pointer-events-auto relative px-3">
+ <UsageLimitReachedCard />
+ </div>
</div>
- </div>
- )}
- <SharedChatNotice sessionId={sessionId} />
- {isTaskBarEnabled && (
- <div className="relative z-10">
- <TaskProgressBar
- todos={getLatestTaskList(messages) ?? []}
- isStreaming={isStreaming}
- />
- </div>
- )}
- <Tooltip open={isLimitReached ? undefined : false}>
- <TooltipTrigger asChild>
- <div>
- <ChatInput
- inputId="chat-input-session"
- onSend={onSend}
- disabled={isInputDisabled}
+ )}
+ <SharedChatNotice sessionId={sessionId} />
+ {isTaskBarEnabled && (
+ <div className="relative z-10">
+ <TaskProgressBar
+ todos={getLatestTaskList(messages) ?? []}
isStreaming={isStreaming}
- isUploadingFiles={isUploadingFiles}
- onStop={onStop}
- onEnqueue={onEnqueue}
- placeholder="What else can I help with?"
- droppedFiles={droppedFiles}
- onDroppedFilesConsumed={onDroppedFilesConsumed}
- hasSession={!!sessionId}
/>
</div>
- </TooltipTrigger>
- <TooltipContent side="top" className="max-w-sm">
- You&apos;ve reached your usage limit. Wait for it to refresh
- or upgrade your plan to continue sending messages.
- </TooltipContent>
- </Tooltip>
- </motion.div>
+ )}
+ <Tooltip open={isLimitReached ? undefined : false}>
+ <TooltipTrigger asChild>
+ <div>
+ <ChatInput
+ inputId="chat-input-session"
+ onSend={guardedOnSend}
+ disabled={isInputDisabled}
+ isStreaming={isStreaming}
+ isUploadingFiles={isUploadingFiles}
+ onStop={onStop}
+ onEnqueue={onEnqueue}
+ placeholder="What else can I help with?"
+ droppedFiles={droppedFiles}
+ onDroppedFilesConsumed={onDroppedFilesConsumed}
+ hasSession={!!sessionId}
+ />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="max-w-sm">
+ You&apos;ve reached your usage limit. Wait for it to
+ refresh or upgrade your plan to continue sending messages.
+ </TooltipContent>
+ </Tooltip>
+ </motion.div>
+ )}
</div>
) : (
<EmptySession
inputLayoutId={inputLayoutId}
isCreatingSession={isCreatingSession}
onCreateSession={onCreateSession}
- onSend={onSend}
+ onSend={guardedOnSend}
isUploadingFiles={isUploadingFiles}
droppedFiles={droppedFiles}
onDroppedFilesConsumed={onDroppedFilesConsumed}
- isAdoptingExpertSession={isAdoptingExpertSession}
+ isInteractionLocked={isSendLocked || !!isAdoptingExpertSession}
isKickoffStarting={isKickoffStarting}
expertName={expertIdentity?.name}
/>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/archived-expert.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/archived-expert.test.tsx
new file mode 100644
index 0000000000..e08415e3ee
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/archived-expert.test.tsx
@@ -0,0 +1,237 @@
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import type { UIDataTypes, UIMessage, UITools } from "ai";
+import { describe, expect, it, vi } from "vitest";
+import { ChatContainer } from "../ChatContainer";
+
+type ChatMessagesContainerProps = {
+ onRetry?: () => void;
+};
+
+type CopilotChatActionsProviderProps = {
+ onSend: (message: string) => void;
+ children: React.ReactNode;
+};
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return { ...actual, useGetFlag: () => false };
+});
+
+vi.mock("@/app/(platform)/copilot/components/ChatInput/ChatInput", () => {
+ function ChatInput() {
+ return <div data-testid="composer" />;
+ }
+
+ return { ChatInput };
+});
+
+vi.mock(
+ "@/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer",
+ () => {
+ function ChatMessagesContainer({ onRetry }: ChatMessagesContainerProps) {
+ return (
+ <div data-testid="messages">
+ <button
+ type="button"
+ data-testid="error-retry"
+ onClick={() => onRetry?.()}
+ />
+ </div>
+ );
+ }
+
+ return { ChatMessagesContainer };
+ },
+);
+
+vi.mock(
+ "@/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts",
+ () => ({
+ useAutoOpenArtifacts: () => undefined,
+ }),
+);
+
+vi.mock(
+ "@/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider",
+ () => {
+ function CopilotChatActionsProvider({
+ onSend,
+ children,
+ }: CopilotChatActionsProviderProps) {
+ return (
+ <>
+ <button
+ type="button"
+ data-testid="provider-send"
+ onClick={() => onSend("Send from a historical tool card")}
+ />
+ {children}
+ </>
+ );
+ }
+
+ return { CopilotChatActionsProvider };
+ },
+);
+
+vi.mock(
+ "@/app/(platform)/copilot/components/UsageLimits/useIsUsageLimitReached",
+ () => ({
+ useIsUsageLimitReached: () => false,
+ }),
+);
+
+const userMessage: UIMessage<unknown, UIDataTypes, UITools> = {
+ id: "m1",
+ role: "user",
+ parts: [{ type: "text", text: "Plan my week" }],
+};
+
+const baseProps = {
+ messages: [userMessage],
+ status: "error",
+ error: new Error("boom"),
+ sessionId: "s1",
+ isLoadingSession: false,
+ isCreatingSession: false,
+ onCreateSession: vi.fn(),
+ onStop: vi.fn(),
+};
+
+const mariaIdentity = {
+ id: "expert-maria",
+ name: "Maria",
+ avatarUrl: null,
+ role: "Marketing Strategist",
+ isArchived: false,
+ readOnlyReason: null,
+};
+
+describe("ChatContainer — archived expert", () => {
+ it("replaces the composer with a read-only notice for a fired expert", () => {
+ render(
+ <ChatContainer
+ {...baseProps}
+ onSend={vi.fn()}
+ expertIdentity={{ ...mariaIdentity, isArchived: true }}
+ />,
+ );
+
+ expect(screen.getByTestId("archived-expert-notice").textContent).toContain(
+ "Maria was fired — this thread is read-only",
+ );
+ expect(screen.queryByTestId("composer")).toBeNull();
+ });
+
+ it("keeps the composer for an active expert", () => {
+ render(
+ <ChatContainer
+ {...baseProps}
+ onSend={vi.fn()}
+ expertIdentity={mariaIdentity}
+ />,
+ );
+
+ expect(screen.getByTestId("composer")).toBeDefined();
+ expect(screen.queryByTestId("archived-expert-notice")).toBeNull();
+ });
+
+ it("never resends through error retry on an archived thread", () => {
+ const onSend = vi.fn();
+ render(
+ <ChatContainer
+ {...baseProps}
+ onSend={onSend}
+ expertIdentity={{ ...mariaIdentity, isArchived: true }}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("error-retry"));
+
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
+ it("never resends through error retry while expert identity is unresolved", () => {
+ const onSend = vi.fn();
+ render(
+ <ChatContainer
+ {...baseProps}
+ onSend={onSend}
+ isResolvingExpertIdentity
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("error-retry"));
+
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
+ it("blocks send actions from historical tool cards on an archived thread", () => {
+ const onSend = vi.fn();
+ render(
+ <ChatContainer
+ {...baseProps}
+ onSend={onSend}
+ expertIdentity={{ ...mariaIdentity, isArchived: true }}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("provider-send"));
+
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
+ it("blocks historical tool-card sends while expert identity is unresolved", () => {
+ const onSend = vi.fn();
+ render(
+ <ChatContainer
+ {...baseProps}
+ onSend={onSend}
+ isResolvingExpertIdentity
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("provider-send"));
+
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
+ it("retries the last user message on an active thread", () => {
+ const onSend = vi.fn();
+ render(
+ <ChatContainer
+ {...baseProps}
+ onSend={onSend}
+ expertIdentity={mariaIdentity}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("error-retry"));
+
+ // Non-kickoff retries carry no attachments and no kickoff metadata.
+ expect(onSend).toHaveBeenCalledWith(
+ "Plan my week",
+ undefined,
+ undefined,
+ undefined,
+ );
+ });
+
+ it("keeps historical tool-card sends available on an active thread", () => {
+ const onSend = vi.fn();
+ render(
+ <ChatContainer
+ {...baseProps}
+ onSend={onSend}
+ expertIdentity={mariaIdentity}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("provider-send"));
+
+ expect(onSend).toHaveBeenCalledWith("Send from a historical tool card");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/fail-closed-expert.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/fail-closed-expert.test.tsx
new file mode 100644
index 0000000000..600d8b8e90
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/fail-closed-expert.test.tsx
@@ -0,0 +1,240 @@
+import { getListExpertIdentitiesQueryKey } from "@/app/api/__generated__/endpoints/experts/experts";
+import { getListExpertIdentitiesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { server } from "@/mocks/mock-server";
+import { act, render, screen, waitFor } from "@/tests/integrations/test-utils";
+import { http, HttpResponse } from "msw";
+import { useQueryClient } from "@tanstack/react-query";
+import { describe, expect, it, vi } from "vitest";
+import { resolveExpertIdentity, useExpertMap } from "../../../useExpertMap";
+import { ChatContainer } from "../ChatContainer";
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return {
+ ...actual,
+ // Only HIRE_EXPERTS is on: useExpertMap runs, artifacts/task-bar stay off.
+ useGetFlag: (flag: string) => flag === "hire-experts",
+ };
+});
+
+vi.mock("@/app/(platform)/copilot/components/ChatInput/ChatInput", () => ({
+ ChatInput: ({ disabled }: { disabled?: boolean }) => (
+ <button type="button" data-testid="composer" disabled={disabled} />
+ ),
+}));
+
+vi.mock(
+ "@/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer",
+ () => ({
+ ChatMessagesContainer: () => <div data-testid="messages" />,
+ }),
+);
+
+vi.mock(
+ "@/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts",
+ () => ({
+ useAutoOpenArtifacts: () => undefined,
+ }),
+);
+
+vi.mock(
+ "@/app/(platform)/copilot/components/UsageLimits/useIsUsageLimitReached",
+ () => ({
+ useIsUsageLimitReached: () => false,
+ }),
+);
+
+const baseProps = {
+ messages: [],
+ status: "ready",
+ error: undefined,
+ sessionId: "s1",
+ isLoadingSession: false,
+ isCreatingSession: false,
+ onCreateSession: vi.fn(),
+ onSend: vi.fn(),
+ onStop: vi.fn(),
+};
+
+const maria: Expert = {
+ id: "expert-maria",
+ name: "Maria",
+ avatar_url: null,
+ role: "Marketing Strategist",
+ tagline: null,
+ bio: null,
+ skills: [],
+ identity: "You are Maria.",
+ voice_preferences: "Warm.",
+ boundaries: "Honest.",
+ protected_soul_rules: [],
+ is_template: false,
+ source_template_id: "template-maria",
+ is_archived: false,
+ workflows: [],
+};
+
+// The session already knows its expert; identity is resolved by the SAME
+// endpoint→map→resolve chain production uses, so a fail-open regression here
+// would surface as a writable thread rather than being masked by a hand-set prop.
+function ExpertThreadHarness({ activeExpertId }: { activeExpertId: string }) {
+ const queryClient = useQueryClient();
+ const { expertsById, hasExpertsSettled, hasExpertsErrored } = useExpertMap();
+ const expertIdentity = resolveExpertIdentity(activeExpertId, expertsById, {
+ settled: hasExpertsSettled,
+ errored: hasExpertsErrored,
+ });
+ return (
+ <>
+ <button
+ type="button"
+ data-testid="refresh-identities"
+ onClick={() =>
+ void queryClient.invalidateQueries({
+ queryKey: getListExpertIdentitiesQueryKey(),
+ })
+ }
+ />
+ <ChatContainer
+ {...baseProps}
+ expertIdentity={expertIdentity}
+ isResolvingExpertIdentity={!hasExpertsSettled}
+ />
+ </>
+ );
+}
+
+describe("Copilot expert thread — fail-closed identity", () => {
+ it("keeps a fired expert's thread read-only with their real name", async () => {
+ let requestedUrl: string | null = null;
+ server.use(
+ http.get("*/api/experts/identities", ({ request }) => {
+ requestedUrl = request.url;
+ return HttpResponse.json([{ ...maria, is_archived: true }]);
+ }),
+ );
+
+ render(<ExpertThreadHarness activeExpertId="expert-maria" />);
+
+ const notice = await screen.findByTestId("archived-expert-notice");
+ expect(notice.textContent).toContain(
+ "Maria was fired — this thread is read-only",
+ );
+ expect(screen.queryByTestId("composer")).toBeNull();
+ expect(requestedUrl).toContain("/api/experts/identities");
+ });
+
+ it("fails closed to read-only when the roster fetch errors", async () => {
+ server.use(
+ http.get("*/api/experts/identities", () =>
+ HttpResponse.json({ detail: "boom" }, { status: 500 }),
+ ),
+ );
+
+ render(<ExpertThreadHarness activeExpertId="expert-maria" />);
+
+ const notice = await screen.findByTestId("archived-expert-notice");
+ expect(notice.textContent).toContain(
+ "is temporarily unavailable — this thread is read-only",
+ );
+ expect(notice.getAttribute("role")).toBe("status");
+ expect(screen.queryByTestId("composer")).toBeNull();
+ });
+
+ it("fails closed with neutral copy when the expert is gone from a loaded roster", async () => {
+ server.use(getListExpertIdentitiesMockHandler([]));
+
+ render(<ExpertThreadHarness activeExpertId="expert-ghost" />);
+
+ const notice = await screen.findByTestId("archived-expert-notice");
+ // An id missing from a settled roster may have been deleted or never have
+ // been ours — claiming it was "fired" would state something we can't know.
+ expect(notice.textContent).toContain(
+ "is no longer available — this thread is read-only",
+ );
+ expect(notice.textContent).not.toContain("was fired");
+ expect(screen.queryByTestId("composer")).toBeNull();
+ });
+
+ it("keeps the composer for an active expert still on the roster", async () => {
+ server.use(getListExpertIdentitiesMockHandler([maria]));
+
+ render(<ExpertThreadHarness activeExpertId="expert-maria" />);
+
+ await waitFor(() =>
+ expect(
+ (screen.getByTestId("composer") as HTMLButtonElement).disabled,
+ ).toBe(false),
+ );
+ expect(screen.queryByTestId("archived-expert-notice")).toBeNull();
+ });
+
+ it("keeps the composer disabled until an expert identity resolves", async () => {
+ let releaseRequest: () => void = () => undefined;
+ const requestGate = new Promise<void>((resolve) => {
+ releaseRequest = resolve;
+ });
+ server.use(
+ http.get("*/api/experts/identities", async () => {
+ await requestGate;
+ return HttpResponse.json([maria]);
+ }),
+ );
+
+ render(<ExpertThreadHarness activeExpertId="expert-maria" />);
+
+ expect((screen.getByTestId("composer") as HTMLButtonElement).disabled).toBe(
+ true,
+ );
+
+ act(() => releaseRequest());
+
+ await waitFor(() =>
+ expect(
+ (screen.getByTestId("composer") as HTMLButtonElement).disabled,
+ ).toBe(false),
+ );
+ });
+
+ it("fails closed while cached identities refetch and if that refetch fails", async () => {
+ let requestCount = 0;
+ let releaseRefetch: () => void = () => undefined;
+ const refetchGate = new Promise<void>((resolve) => {
+ releaseRefetch = resolve;
+ });
+ server.use(
+ http.get("*/api/experts/identities", async () => {
+ requestCount += 1;
+ if (requestCount === 1) return HttpResponse.json([maria]);
+ await refetchGate;
+ return HttpResponse.json({ detail: "boom" }, { status: 500 });
+ }),
+ );
+
+ render(<ExpertThreadHarness activeExpertId="expert-maria" />);
+ await waitFor(() =>
+ expect(
+ (screen.getByTestId("composer") as HTMLButtonElement).disabled,
+ ).toBe(false),
+ );
+
+ act(() => screen.getByTestId("refresh-identities").click());
+ await waitFor(() =>
+ expect(
+ (screen.getByTestId("composer") as HTMLButtonElement).disabled,
+ ).toBe(true),
+ );
+
+ act(() => releaseRefetch());
+
+ const notice = await screen.findByTestId("archived-expert-notice");
+ expect(notice.textContent).toContain(
+ "Maria is temporarily unavailable — this thread is read-only",
+ );
+ expect(screen.queryByTestId("composer")).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/ArchivedExpertNotice.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/ArchivedExpertNotice.tsx
new file mode 100644
index 0000000000..c00240733c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/ArchivedExpertNotice.tsx
@@ -0,0 +1,41 @@
+import type { ExpertReadOnlyReason } from "@/app/(platform)/copilot/useExpertMap";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { ArchiveIcon, CloudOffIcon } from "@hugeicons/core-free-icons";
+
+type Props = {
+ expertName: string;
+ reason: ExpertReadOnlyReason;
+};
+
+// Only `fired` is a fact we can state. An absent id may have been deleted or
+// never have been ours, so it gets neutral copy rather than a firing we can't
+// confirm; a failed roster read is explicitly temporary.
+const NOTICE_COPY: Record<ExpertReadOnlyReason, (name: string) => string> = {
+ fired: (name) => `${name} was fired — this thread is read-only`,
+ unavailable: (name) =>
+ `${name} is temporarily unavailable — this thread is read-only`,
+ unknown: (name) =>
+ `${name} is no longer available — this thread is read-only`,
+};
+
+export function ArchivedExpertNotice({ expertName, reason }: Props) {
+ return (
+ <div className="px-3 pb-6 pt-2">
+ <div
+ data-testid="archived-expert-notice"
+ role="status"
+ className="mx-auto flex w-full max-w-2xl items-center justify-center gap-2 rounded-2xl border border-border bg-muted/40 px-4 py-3 text-center"
+ >
+ <Icon
+ icon={reason === "unavailable" ? CloudOffIcon : ArchiveIcon}
+ size={16}
+ className="text-muted-foreground"
+ />
+ <Text variant="small" className="text-muted-foreground">
+ {NOTICE_COPY[reason](expertName)}
+ </Text>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
index fae4d00951..2f7684cecd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
@@ -537,7 +537,7 @@ export function ChatMessagesContainer({
<span className="text-sm font-medium text-zinc-800">
{expertIdentity.name}
</span>
- {!readOnly && (
+ {!readOnly && !expertIdentity.isArchived && (
<ExpertSchedulesButton
expertId={expertIdentity.id}
expertName={expertIdentity.name}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx
index 19cc75d693..1cf77c9ac9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx
@@ -40,7 +40,7 @@ interface Props {
isUploadingFiles?: boolean;
droppedFiles?: File[];
onDroppedFilesConsumed?: () => void;
- isAdoptingExpertSession?: boolean;
+ isInteractionLocked?: boolean;
isKickoffStarting?: boolean;
expertName?: string;
}
@@ -52,7 +52,7 @@ export function EmptySession({
isUploadingFiles,
droppedFiles,
onDroppedFilesConsumed,
- isAdoptingExpertSession,
+ isInteractionLocked,
isKickoffStarting,
expertName,
}: Props) {
@@ -65,7 +65,7 @@ export function EmptySession({
const pulseChips = usePulseChips();
const { options, recipient, isLoadingRecipient, selectRecipient } =
useRecipientPicker();
- const isComposerDisabled = isCreatingSession || !!isAdoptingExpertSession;
+ const isComposerDisabled = isCreatingSession || !!isInteractionLocked;
const { data: suggestedPromptsResponse, isLoading: isLoadingPrompts } =
useGetV2GetSuggestedPrompts({
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/useRecipientPicker.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/useRecipientPicker.ts
index 1fdee4f994..b1acda1f90 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/useRecipientPicker.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/useRecipientPicker.ts
@@ -10,7 +10,12 @@ const AUTOPILOT_RECIPIENT: RecipientOption = {
};
export function useRecipientPicker() {
- const { expertsById, isLoadingExperts, hasLoadedExperts } = useExpertMap();
+ const {
+ activeExperts,
+ activeExpertIds,
+ isLoadingExperts,
+ hasExpertsSettled,
+ } = useExpertMap();
const [expertIdParam, setExpertIdParam] = useQueryState(
"expertId",
parseAsString,
@@ -22,17 +27,17 @@ export function useRecipientPicker() {
// rejects with a 404 on every send. Drop it so both agree on Autopilot.
useEffect(
function clearUnknownExpertParam() {
- if (!hasLoadedExperts || !expertIdParam) return;
- if (expertsById.has(expertIdParam)) return;
+ if (!hasExpertsSettled || !expertIdParam) return;
+ if (activeExpertIds.has(expertIdParam)) return;
void setExpertIdParam(null);
},
- [hasLoadedExperts, expertIdParam, expertsById, setExpertIdParam],
+ [activeExpertIds, hasExpertsSettled, expertIdParam, setExpertIdParam],
);
const options: RecipientOption[] = [
AUTOPILOT_RECIPIENT,
- ...[...expertsById.entries()].map(([id, expert]) => ({
- id,
+ ...activeExperts.map((expert) => ({
+ id: expert.id,
name: expert.name,
avatarUrl: expert.avatarUrl,
})),
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.ts
index 08e4ca883e..e39e2d01ef 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.ts
@@ -111,10 +111,10 @@ export function isKickoffMessage(message: UIMessage): boolean {
export function shouldClearKickoffParam(
isExpertsEnabled: boolean,
- hasLoadedExperts: boolean,
+ hasExpertsSettled: boolean,
expertId: string | null,
): boolean {
- return !isExpertsEnabled || (hasLoadedExperts && expertId === null);
+ return !isExpertsEnabled || (hasExpertsSettled && expertId === null);
}
export function stripKickoffMessages<T extends UIMessage>(messages: T[]): T[] {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
index 79dda47e1c..1a5ca028eb 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
@@ -24,7 +24,7 @@ import {
import { useExpertKickoff } from "./useExpertKickoff";
import { useCopilotNotifications } from "./useCopilotNotifications";
import { useCopilotStream } from "./useCopilotStream";
-import { useExpertMap } from "./useExpertMap";
+import { resolveExpertIdentity, useExpertMap } from "./useExpertMap";
import { useLoadMoreMessages } from "./useLoadMoreMessages";
import { useSendMessage } from "./useSendMessage";
import { useSessionTitlePoll } from "./useSessionTitlePoll";
@@ -68,19 +68,29 @@ export function useCopilotPage() {
const isExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);
const isBrainDumpEnabled = useGetFlag(Flag.ONBOARDING_BRAIN_DUMP);
const [expertIdParam] = useQueryState("expertId", parseAsString);
+ const expertId = isExpertsEnabled ? expertIdParam : null;
const [kickoffParam, setKickoffParam] = useQueryState(
"kickoff",
parseAsString,
);
- const { expertsById, isLoadingExperts, hasLoadedExperts } = useExpertMap();
+ const {
+ expertsById,
+ isLoadingExperts,
+ hasExpertsSettled,
+ hasExpertsErrored,
+ } = useExpertMap();
const validExpertIdParam =
expertIdParam && isValidUUID(expertIdParam) ? expertIdParam : null;
- const expertId =
- isExpertsEnabled &&
- hasLoadedExperts &&
- validExpertIdParam &&
- expertsById.has(validExpertIdParam)
- ? validExpertIdParam
+ // Day one only fires for an expert we can still address. `onKickoff` writes
+ // its opening turn through `sendNewMessage`, bypassing the `onSend` archive
+ // guard, so a bogus id, an unreadable roster or a fired expert has to fall
+ // through to the read-only thread rather than reach the kickoff path.
+ const kickoffExpert = validExpertIdParam
+ ? expertsById.get(validExpertIdParam)
+ : undefined;
+ const kickoffExpertId =
+ isExpertsEnabled && hasExpertsSettled && kickoffExpert?.isArchived === false
+ ? kickoffExpert.id
: null;
const isKickoffResolving =
isExpertsEnabled &&
@@ -90,13 +100,19 @@ export function useCopilotPage() {
useEffect(() => {
if (kickoffParam !== "1") return;
- if (!shouldClearKickoffParam(isExpertsEnabled, hasLoadedExperts, expertId))
+ if (
+ !shouldClearKickoffParam(
+ isExpertsEnabled,
+ hasExpertsSettled,
+ kickoffExpertId,
+ )
+ )
return;
void setKickoffParam(null, { history: "replace" });
}, [
- expertId,
- hasLoadedExperts,
+ hasExpertsSettled,
isExpertsEnabled,
+ kickoffExpertId,
kickoffParam,
setKickoffParam,
]);
@@ -129,10 +145,19 @@ export function useCopilotPage() {
// NEXT session will address, and it is absent whenever a thread is reached
// from global search, a bookmark or a shared link.
const activeExpertId = sessionId ? sessionExpertId : expertId;
- const expertIdentity =
- isExpertsEnabled && activeExpertId
- ? (expertsById.get(activeExpertId) ?? null)
- : null;
+ const expertIdentity = useMemo(
+ () =>
+ resolveExpertIdentity(activeExpertId, expertsById, {
+ settled: hasExpertsSettled,
+ errored: hasExpertsErrored,
+ }),
+ [activeExpertId, expertsById, hasExpertsErrored, hasExpertsSettled],
+ );
+ const isResolvingExpertIdentity = Boolean(
+ isExpertsEnabled && activeExpertId && !hasExpertsSettled,
+ );
+ const isExpertSendLocked =
+ isResolvingExpertIdentity || Boolean(expertIdentity?.isArchived);
const {
messages: currentMessages,
@@ -258,6 +283,7 @@ export function useCopilotPage() {
const hasAttachments =
(files?.length ?? 0) > 0 || (workspaceFiles?.length ?? 0) > 0;
if (!trimmed && !hasAttachments) return;
+ if (isExpertSendLocked) return;
// Sending anything retires the greeting for good: flag it done on
// the server (kept in the DB, just never shown again) and cache the
@@ -318,11 +344,15 @@ export function useCopilotPage() {
await sendNewMessage(message, files, workspaceFiles, metadata);
}
- useWorkflowImportAutoSubmit({ onSend, setPendingFileParts });
+ useWorkflowImportAutoSubmit({
+ onSend,
+ setPendingFileParts,
+ isSendLocked: isExpertSendLocked,
+ });
const { isKickoffStarting } = useExpertKickoff({
userId: user?.id ?? null,
- expertId,
+ expertId: kickoffExpertId,
kickoff: isExpertsEnabled && kickoffParam === "1",
sessionId,
sessionExpertId,
@@ -384,6 +414,7 @@ export function useCopilotPage() {
sessionDryRun,
sessionChatStatus,
expertIdentity,
+ isResolvingExpertIdentity,
isAdoptingExpertSession,
isKickoffStarting: isKickoffResolving || isKickoffStarting,
};
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts
index fd25a6859c..436c171bd2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts
@@ -1,21 +1,77 @@
-import { useListExperts } from "@/app/api/__generated__/endpoints/experts/experts";
+import { useListExpertIdentities } from "@/app/api/__generated__/endpoints/experts/experts";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { useMemo } from "react";
+/**
+ * Why a thread is read-only. `fired` is the only reason we can state as fact;
+ * `unavailable` is a transient roster-read failure and `unknown` covers an id
+ * that is simply absent from a settled roster (deleted, wrong, or never ours).
+ */
+export type ExpertReadOnlyReason = "fired" | "unavailable" | "unknown";
+
export interface ExpertIdentity {
id: string;
name: string;
avatarUrl: string | null;
role: string | null;
+ isArchived: boolean;
+ readOnlyReason: ExpertReadOnlyReason | null;
}
export type ExpertIdentityMap = Map<string, ExpertIdentity>;
const EMPTY_MAP: ExpertIdentityMap = new Map();
+const EMPTY_EXPERTS: ExpertIdentity[] = [];
+const EMPTY_IDS: ReadonlySet<string> = new Set();
+
+const FALLBACK_ARCHIVED_NAME = "This expert";
+/**
+ * Resolve the identity a chat session should render for `activeExpertId`.
+ *
+ * Fail closed: once the roster query has SETTLED (success or error), a
+ * session pointing at an expert we can't resolve is treated as archived
+ * (read-only history, generic name) — never a writable plain Autopilot
+ * thread. A cached identity can still supply its name after a failed
+ * refetch, but is marked unavailable and read-only. Passing the settled
+ * flag rather than the success flag is load-bearing: a failed roster fetch
+ * must not fail open into a writable composer.
+ */
+export function resolveExpertIdentity(
+ activeExpertId: string | null,
+ expertsById: ExpertIdentityMap,
+ { settled, errored }: { settled: boolean; errored: boolean },
+): ExpertIdentity | null {
+ if (!activeExpertId) return null;
+ const found = expertsById.get(activeExpertId);
+ if (found) {
+ return errored
+ ? { ...found, isArchived: true, readOnlyReason: "unavailable" }
+ : found;
+ }
+ if (!settled) return null;
+ return {
+ id: activeExpertId,
+ name: FALLBACK_ARCHIVED_NAME,
+ avatarUrl: null,
+ role: null,
+ isArchived: true,
+ readOnlyReason: errored ? "unavailable" : "unknown",
+ };
+}
+
+/**
+ * Identity map for expert-scoped chat sessions.
+ *
+ * CONTRACT: `expertsById` deliberately includes ARCHIVED experts — it is the
+ * identity source for read-only fired-expert threads, so it must keep
+ * resolving names after an expert leaves the active roster or a background
+ * refetch fails. Consumers that present experts as addressable receive the
+ * separate `activeExperts` projection instead of iterating this map.
+ */
export function useExpertMap() {
const isExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);
- const expertsQuery = useListExperts({
+ const expertsQuery = useListExpertIdentities({
query: {
enabled: isExpertsEnabled,
select: (response) =>
@@ -26,27 +82,52 @@ export function useExpertMap() {
// Memoized on purpose: the identities read out of this map are passed as
// props (`expertIdentity`) down the whole chat tree, so rebuilding it every
// render would hand every consumer a fresh object identity each time.
- const expertsById = useMemo(() => {
+ const expertCollections = useMemo(() => {
const experts = expertsQuery.data;
- if (!experts) return EMPTY_MAP;
- return new Map(
- experts.map((expert) => [
- expert.id,
- {
- id: expert.id,
- name: expert.name,
- avatarUrl: expert.avatar_url ?? null,
- role: expert.role ?? null,
- },
- ]),
- );
+ if (!experts)
+ return {
+ expertsById: EMPTY_MAP,
+ activeExperts: EMPTY_EXPERTS,
+ activeExpertIds: EMPTY_IDS,
+ };
+ const identities = experts.map((expert) => ({
+ id: expert.id,
+ name: expert.name,
+ avatarUrl: expert.avatar_url ?? null,
+ role: expert.role,
+ isArchived: expert.is_archived,
+ readOnlyReason: expert.is_archived ? ("fired" as const) : null,
+ }));
+ const activeExperts = identities.filter((expert) => !expert.isArchived);
+ return {
+ expertsById: new Map(identities.map((expert) => [expert.id, expert])),
+ activeExperts,
+ activeExpertIds: new Set(activeExperts.map((expert) => expert.id)),
+ };
}, [expertsQuery.data]);
+ const canAddressExperts = isExpertsEnabled && !expertsQuery.isError;
+
return {
- expertsById: isExpertsEnabled ? expertsById : EMPTY_MAP,
- // A disabled query reports `isPending` forever, so both flags stay gated
+ expertsById: isExpertsEnabled ? expertCollections.expertsById : EMPTY_MAP,
+ activeExperts: canAddressExperts
+ ? expertCollections.activeExperts
+ : EMPTY_EXPERTS,
+ // Same membership as `activeExperts`, as a set, so callers testing "can the
+ // user still address this id?" do a constant-time lookup instead of a scan.
+ activeExpertIds: canAddressExperts
+ ? expertCollections.activeExpertIds
+ : EMPTY_IDS,
+ // A disabled query reports `isPending` forever, so all flags stay gated
// on the feature flag to remain honest when experts are off.
- isLoadingExperts: isExpertsEnabled && expertsQuery.isPending,
- hasLoadedExperts: isExpertsEnabled && expertsQuery.isSuccess,
+ isLoadingExperts: isExpertsEnabled && expertsQuery.isFetching,
+ hasExpertsErrored:
+ isExpertsEnabled && expertsQuery.isError && !expertsQuery.isFetching,
+ // Settled = success OR error. resolveExpertIdentity keys off this so an
+ // errored roster fetch fails closed (read-only) instead of open.
+ hasExpertsSettled:
+ isExpertsEnabled &&
+ !expertsQuery.isFetching &&
+ (expertsQuery.isSuccess || expertsQuery.isError),
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.test.tsx
new file mode 100644
index 0000000000..02259456df
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.test.tsx
@@ -0,0 +1,61 @@
+import { renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useCopilotUIStore } from "./store";
+import { useWorkflowImportAutoSubmit } from "./useWorkflowImportAutoSubmit";
+
+const PROMPT = "Build this workflow";
+
+function storeAutoSubmitPrompt() {
+ window.sessionStorage.setItem("importWorkflowPrompt", PROMPT);
+ window.sessionStorage.setItem("importWorkflowAutosubmit", "true");
+}
+
+beforeEach(() => {
+ window.sessionStorage.clear();
+ window.history.replaceState({}, "", "/copilot");
+ useCopilotUIStore.getState().setInitialPrompt(null);
+});
+
+describe("useWorkflowImportAutoSubmit", () => {
+ it("waits for unresolved expert identity before consuming or submitting the prompt", async () => {
+ const onSend = vi.fn().mockResolvedValue(undefined);
+ const setPendingFileParts = vi.fn();
+ storeAutoSubmitPrompt();
+
+ const { rerender } = renderHook(
+ ({ isSendLocked }) =>
+ useWorkflowImportAutoSubmit({
+ onSend,
+ setPendingFileParts,
+ isSendLocked,
+ }),
+ { initialProps: { isSendLocked: true } },
+ );
+
+ expect(onSend).not.toHaveBeenCalled();
+ expect(window.sessionStorage.getItem("importWorkflowPrompt")).toBe(PROMPT);
+
+ rerender({ isSendLocked: false });
+
+ await waitFor(() => expect(onSend).toHaveBeenCalledWith(PROMPT));
+ expect(window.sessionStorage.getItem("importWorkflowPrompt")).toBeNull();
+ });
+
+ it("does not consume or submit an auto-submit prompt for an archived expert", () => {
+ const onSend = vi.fn().mockResolvedValue(undefined);
+ const setPendingFileParts = vi.fn();
+ storeAutoSubmitPrompt();
+
+ renderHook(() =>
+ useWorkflowImportAutoSubmit({
+ onSend,
+ setPendingFileParts,
+ isSendLocked: true,
+ }),
+ );
+
+ expect(onSend).not.toHaveBeenCalled();
+ expect(setPendingFileParts).not.toHaveBeenCalled();
+ expect(window.sessionStorage.getItem("importWorkflowPrompt")).toBe(PROMPT);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.ts
index 30582984e5..1296a8b40f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.ts
@@ -97,15 +97,17 @@ function extractPromptFromUrl(): {
export function useWorkflowImportAutoSubmit({
onSend,
setPendingFileParts,
+ isSendLocked = false,
}: {
onSend: (message: string) => Promise<void>;
setPendingFileParts: (parts: FileUIPart[]) => void;
+ isSendLocked?: boolean;
}) {
const { setInitialPrompt } = useCopilotUIStore();
const hasProcessedUrlPrompt = useRef(false);
useEffect(() => {
- if (hasProcessedUrlPrompt.current) return;
+ if (isSendLocked || hasProcessedUrlPrompt.current) return;
const urlPrompt = extractPromptFromUrl();
if (!urlPrompt) return;
@@ -122,5 +124,5 @@ export function useWorkflowImportAutoSubmit({
} else {
setInitialPrompt(urlPrompt.prompt);
}
- }, [onSend, setInitialPrompt, setPendingFileParts]);
+ }, [isSendLocked, onSend, setInitialPrompt, setPendingFileParts]);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsx
index 28da36cadb..6d018939e1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsx
@@ -324,4 +324,18 @@ describe("Marketplace ExpertsSection", () => {
expect(await screen.findByText("Meet the AI Experts")).toBeDefined();
expect(await screen.findByText("Hired")).toBeDefined();
});
+
+ test("template becomes hireable again once the expert is fired", async () => {
+ server.use(
+ getListExpertTemplatesMockHandler([mariaTemplate]),
+ getListExpertsMockHandler([{ ...hiredMaria, is_archived: true }]),
+ );
+
+ renderMarketplace();
+
+ expect(await screen.findByText("Meet the AI Experts")).toBeDefined();
+ await screen.findByText("Maria");
+ expect(screen.getByText("Hire")).toBeDefined();
+ expect(screen.queryByText("Hired")).toBeNull();
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/components/ExpertProfileSheet/useExpertProfileSheet.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/components/ExpertProfileSheet/useExpertProfileSheet.tsx
index 815e90542c..acb419f95e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/components/ExpertProfileSheet/useExpertProfileSheet.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/components/ExpertProfileSheet/useExpertProfileSheet.tsx
@@ -1,6 +1,5 @@
import {
getGetExpertQueryKey,
- getListExpertsQueryKey,
useHireExpert,
useListExperts,
useUpdateExpertSoul,
@@ -13,6 +12,7 @@ import {
buildVoicePreferences,
type VoicePickResult,
} from "@/components/organisms/VoicePicker/helpers";
+import { invalidateExpertRosterQueries } from "@/services/experts/invalidate-experts";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useRef, useState } from "react";
@@ -76,9 +76,7 @@ export function useExpertProfileSheet(
try {
const response = await hireExpert({ data: { template_id: expert.id } });
const result = response.data as HireResult;
- await queryClient.invalidateQueries({
- queryKey: getListExpertsQueryKey(),
- });
+ await invalidateExpertRosterQueries(queryClient);
pendingCelebrationRef.current = result;
// Offer the voice pick when the persona ships writing samples; otherwise
// finish with the classic celebration toast.
@@ -123,7 +121,7 @@ export function useExpertProfileSheet(
// this, a Soul edit within the stale window would silently write that
// old description back over the chosen voice.
await Promise.all([
- queryClient.invalidateQueries({ queryKey: getListExpertsQueryKey() }),
+ invalidateExpertRosterQueries(queryClient),
queryClient.invalidateQueries({
queryKey: getGetExpertQueryKey(hired.id),
}),
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts
index fac73955c5..ae9ffa4738 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts
@@ -19,11 +19,12 @@ export function useExpertsSection() {
query: { select: (x) => x.data as Expert[], enabled: isLoggedIn },
});
- const hiredTemplateIds = new Set(
- (expertsQuery.data ?? [])
- .map((expert) => expert.source_template_id)
- .filter((id): id is string => Boolean(id)),
- );
+ const hiredTemplateIds = new Set<string>();
+ for (const expert of expertsQuery.data ?? []) {
+ if (!expert.is_archived && expert.source_template_id) {
+ hiredTemplateIds.add(expert.source_template_id);
+ }
+ }
return {
templates: templatesQuery.data ?? [],
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx
index 95c8c69fe9..4e35c78243 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx
@@ -1,4 +1,6 @@
import {
+ getArchiveExpertMockHandler,
+ getGetExpertDetachPreviewMockHandler,
getGetExpertMockHandler,
getResumeExpertSchedulesMockHandler,
} from "@/app/api/__generated__/endpoints/experts/experts.msw";
@@ -37,10 +39,13 @@ vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
};
});
-const notFoundMock = vi.hoisted(() => vi.fn());
+const { notFoundMock, pushMock } = vi.hoisted(() => ({
+ notFoundMock: vi.fn(),
+ pushMock: vi.fn(),
+}));
vi.mock("next/navigation", () => ({
useRouter: () => ({
- push: vi.fn(),
+ push: pushMock,
replace: vi.fn(),
prefetch: vi.fn(),
back: vi.fn(),
@@ -120,6 +125,7 @@ beforeEach(() => {
afterEach(() => {
setFlagStatusMock.mockReturnValue({ enabled: true, ready: true });
+ pushMock.mockReset();
});
describe("ExpertDetailPage", () => {
@@ -190,4 +196,37 @@ describe("ExpertDetailPage", () => {
fireEvent.click(screen.getByRole("button", { name: "Resume schedules" }));
await waitFor(() => expect(resumeSpy).toHaveBeenCalled());
});
+
+ test("fires the expert from the header menu and returns to the team page", async () => {
+ const archiveSpy = vi.fn();
+ server.use(
+ getGetExpertDetachPreviewMockHandler({
+ schedule_names: ["Content Calendar"],
+ trigger_names: [],
+ }),
+ getArchiveExpertMockHandler(archiveSpy),
+ );
+
+ render(<ExpertDetailPage />);
+
+ await screen.findByRole("heading", { name: "Maria" });
+ fireEvent.pointerDown(screen.getByTestId("expert-detail-actions"), {
+ button: 0,
+ });
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: /Fire Maria/ }),
+ );
+
+ const dialog = await screen.findByRole("dialog", { name: "Fire Maria?" });
+ expect(
+ await within(dialog).findByText("1 automation will pause."),
+ ).toBeDefined();
+
+ const confirm = await screen.findByTestId("fire-expert-confirm");
+ await waitFor(() => expect(confirm.hasAttribute("disabled")).toBe(false));
+ fireEvent.click(confirm);
+
+ await waitFor(() => expect(archiveSpy).toHaveBeenCalled());
+ await waitFor(() => expect(pushMock).toHaveBeenCalledWith("/team"));
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx
index b770f32d7a..180cfdbe9e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx
@@ -16,8 +16,10 @@ import { Flag, useFlagStatus } from "@/services/feature-flags/use-get-flag";
import { ArrowLeft02Icon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
import Link from "next/link";
-import { notFound, useParams } from "next/navigation";
+import { notFound, useParams, useRouter } from "next/navigation";
import { getLastRunLabel } from "../helpers";
+import { FireExpertDialog } from "../components/FireExpertDialog/FireExpertDialog";
+import { FireExpertMenu } from "../components/FireExpertMenu/FireExpertMenu";
import { ExpertAboutSection } from "./components/ExpertAboutSection";
import { ExpertSchedulesSection } from "./components/ExpertSchedulesSection";
import { ExpertWorkflowsSection } from "./components/ExpertWorkflowsSection";
@@ -41,6 +43,7 @@ function BackToTeamLink() {
export default function ExpertDetailPage() {
const { expertId } = useParams<{ expertId: string }>();
+ const router = useRouter();
const { enabled, ready } = useFlagStatus(Flag.HIRE_EXPERTS);
const {
expert,
@@ -53,6 +56,9 @@ export default function ExpertDetailPage() {
closePicker,
resumeSchedules,
isResuming,
+ isFireOpen,
+ openFire,
+ closeFire,
} = useExpertDetailPage({
expertId,
enabled: Boolean(enabled) && ready,
@@ -123,7 +129,7 @@ export default function ExpertDetailPage() {
<p className="mt-1.5 text-base text-zinc-500">{expert.tagline}</p>
) : null}
</div>
- <div className="shrink-0">
+ <div className="flex shrink-0 items-center gap-2">
<Button
as="NextLink"
href={`/copilot?expertId=${expert.id}`}
@@ -132,6 +138,12 @@ export default function ExpertDetailPage() {
>
Chat
</Button>
+ <FireExpertMenu
+ expertName={expert.name}
+ onFire={openFire}
+ testId="expert-detail-actions"
+ triggerClassName="bg-white/70 text-zinc-500 ring-1 ring-inset ring-black/5 hover:bg-white hover:text-zinc-800"
+ />
</div>
</header>
@@ -189,6 +201,14 @@ export default function ExpertDetailPage() {
open={isPickerOpen}
onClose={closePicker}
/>
+
+ <FireExpertDialog
+ expertId={expert.id}
+ expertName={expert.name}
+ open={isFireOpen}
+ onClose={closeFire}
+ onFired={() => router.push("/team")}
+ />
</main>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/useExpertDetailPage.ts b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/useExpertDetailPage.ts
index 4194a7c4bc..9c7737bdc4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/useExpertDetailPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/useExpertDetailPage.ts
@@ -33,6 +33,8 @@ export function useExpertDetailPage({ expertId, enabled }: Args) {
? getExpertSchedules(expert, schedulesQuery.data ?? [])
: [];
+ const [isFireOpen, setIsFireOpen] = useState(false);
+
const { mutate: resumeSchedules, isPending: isResuming } =
useResumeExpertSchedules({
mutation: {
@@ -55,6 +57,14 @@ export function useExpertDetailPage({ expertId, enabled }: Args) {
await Promise.all([expertQuery.refetch(), schedulesQuery.refetch()]);
}
+ function openFire() {
+ setIsFireOpen(true);
+ }
+
+ function closeFire() {
+ setIsFireOpen(false);
+ }
+
return {
expert,
isLoading: enabled && (expertQuery.isLoading || schedulesQuery.isLoading),
@@ -69,5 +79,8 @@ export function useExpertDetailPage({ expertId, enabled }: Args) {
closePicker: () => setIsPickerOpen(false),
resumeSchedules: () => resumeSchedules({ expertId }),
isResuming,
+ isFireOpen,
+ openFire,
+ closeFire,
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx
index bef49203f8..9b585c0584 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx
@@ -1,10 +1,14 @@
import {
+ getArchiveExpertMockHandler,
+ getArchiveExpertMockHandler401,
+ getGetExpertDetachPreviewMockHandler,
getListExpertsMockHandler,
getListExpertsMockHandler401,
getResumeExpertSchedulesMockHandler,
getUpdateExpertSoulMockHandler,
getUpdateExpertSoulMockHandler422,
} from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import { delay, http, HttpResponse } from "msw";
import { getGetV1ListExecutionSchedulesForAUserMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";
import { Expert } from "@/app/api/__generated__/models/expert";
import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
@@ -14,6 +18,7 @@ import {
render,
screen,
waitFor,
+ within,
} from "@/tests/integrations/test-utils";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
@@ -474,6 +479,263 @@ describe("TeamPage", () => {
expect(screen.getByRole("dialog", { name: "Maria's Soul" })).toBeDefined();
});
+ test("states what firing pauses from the detach preview", async () => {
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetExpertDetachPreviewMockHandler({
+ schedule_names: ["Content Calendar"],
+ trigger_names: ["Inbox watcher"],
+ }),
+ );
+
+ render(<TeamPage />);
+
+ await screen.findByText("Maria");
+ fireEvent.pointerDown(screen.getByTestId("expert-card-actions"), {
+ button: 0,
+ });
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: /Fire Maria/ }),
+ );
+
+ const dialog = await screen.findByRole("dialog", { name: "Fire Maria?" });
+ expect(
+ within(dialog).getByText("Installed workflows stay in your library."),
+ ).toBeDefined();
+ expect(
+ await within(dialog).findByText("2 automations will pause."),
+ ).toBeDefined();
+ expect(
+ within(dialog).getByText(
+ "Any chat history stays available but read-only.",
+ ),
+ ).toBeDefined();
+ expect(within(dialog).getByText("Their work stays yours.")).toBeDefined();
+ expect(within(dialog).getByText("Content Calendar")).toBeDefined();
+ expect(within(dialog).getByText("Inbox watcher")).toBeDefined();
+ });
+
+ test("fires an expert and drops them from the roster with a re-hire toast", async () => {
+ let listRequests = 0;
+ const archiveSpy = vi.fn();
+ server.use(
+ getListExpertsMockHandler(() => {
+ listRequests += 1;
+ return listRequests === 1 ? [hiredMaria] : [];
+ }),
+ getGetExpertDetachPreviewMockHandler({
+ schedule_names: [],
+ trigger_names: [],
+ }),
+ getArchiveExpertMockHandler(archiveSpy),
+ );
+
+ render(<TeamPage />);
+
+ await screen.findByText("Maria");
+ fireEvent.pointerDown(screen.getByTestId("expert-card-actions"), {
+ button: 0,
+ });
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: /Fire Maria/ }),
+ );
+ const confirm = await screen.findByTestId("fire-expert-confirm");
+ await waitFor(() => expect(confirm.hasAttribute("disabled")).toBe(false));
+ fireEvent.click(confirm);
+
+ await waitFor(() => expect(archiveSpy).toHaveBeenCalled());
+ await waitFor(() => expect(screen.queryByText("Maria")).toBeNull());
+ expect(listRequests).toBeGreaterThan(1);
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ description: "You can re-hire Maria anytime from the marketplace.",
+ }),
+ );
+ });
+
+ test("ignores escape while the fire request is in flight", async () => {
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetExpertDetachPreviewMockHandler({
+ schedule_names: [],
+ trigger_names: [],
+ }),
+ http.delete("*/api/experts/expert-maria", async () => {
+ await delay(80);
+ return new HttpResponse(null, { status: 204 });
+ }),
+ );
+
+ render(<TeamPage />);
+
+ await screen.findByText("Maria");
+ fireEvent.pointerDown(screen.getByTestId("expert-card-actions"), {
+ button: 0,
+ });
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: /Fire Maria/ }),
+ );
+ const confirm = await screen.findByTestId("fire-expert-confirm");
+ await waitFor(() => expect(confirm.hasAttribute("disabled")).toBe(false));
+ fireEvent.click(confirm);
+
+ // "Keep Maria" is disabled during the request, so ESC must not be an
+ // escape hatch that drops the user out before the outcome is known.
+ const dialog = await screen.findByRole("dialog", { name: "Fire Maria?" });
+ fireEvent.keyDown(dialog, { key: "Escape", code: "Escape" });
+ expect(screen.getByRole("dialog", { name: "Fire Maria?" })).toBeDefined();
+
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog", { name: "Fire Maria?" })).toBeNull(),
+ );
+ });
+
+ test("blocks firing until the detach preview resolves", async () => {
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ http.get("*/api/experts/expert-maria/detach-preview", async () => {
+ await delay(60);
+ return HttpResponse.json({
+ schedule_names: [],
+ trigger_names: [],
+ });
+ }),
+ );
+
+ render(<TeamPage />);
+
+ await screen.findByText("Maria");
+ fireEvent.pointerDown(screen.getByTestId("expert-card-actions"), {
+ button: 0,
+ });
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: /Fire Maria/ }),
+ );
+
+ const dialog = await screen.findByRole("dialog", { name: "Fire Maria?" });
+ expect(within(dialog).getByText("Checking what will pause…")).toBeDefined();
+ expect(
+ screen.getByTestId("fire-expert-confirm").hasAttribute("disabled"),
+ ).toBe(true);
+
+ await waitFor(() =>
+ expect(
+ screen.getByTestId("fire-expert-confirm").hasAttribute("disabled"),
+ ).toBe(false),
+ );
+ });
+
+ test("surfaces an error with retry when the detach preview fails", async () => {
+ let previewRequests = 0;
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ http.get("*/api/experts/expert-maria/detach-preview", () => {
+ previewRequests += 1;
+ if (previewRequests === 1) {
+ return new HttpResponse(null, { status: 404 });
+ }
+ return HttpResponse.json({
+ schedule_names: [],
+ trigger_names: [],
+ });
+ }),
+ );
+
+ render(<TeamPage />);
+
+ await screen.findByText("Maria");
+ fireEvent.pointerDown(screen.getByTestId("expert-card-actions"), {
+ button: 0,
+ });
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: /Fire Maria/ }),
+ );
+
+ const dialog = await screen.findByRole("dialog", { name: "Fire Maria?" });
+ expect(
+ await within(dialog).findByText(
+ "We couldn't preview what pauses, but you can still fire them.",
+ ),
+ ).toBeDefined();
+ expect(
+ screen.getByTestId("fire-expert-confirm").hasAttribute("disabled"),
+ ).toBe(false);
+
+ fireEvent.click(screen.getByTestId("fire-preview-retry"));
+
+ expect(
+ await within(dialog).findByText("No automations will pause."),
+ ).toBeDefined();
+ expect(screen.queryByTestId("fire-preview-retry")).toBeNull();
+ });
+
+ test("fires the expert even when the detach preview fails", async () => {
+ const archiveSpy = vi.fn();
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ http.get(
+ "*/api/experts/expert-maria/detach-preview",
+ () => new HttpResponse(null, { status: 404 }),
+ ),
+ getArchiveExpertMockHandler(archiveSpy),
+ );
+
+ render(<TeamPage />);
+
+ await screen.findByText("Maria");
+ fireEvent.pointerDown(screen.getByTestId("expert-card-actions"), {
+ button: 0,
+ });
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: /Fire Maria/ }),
+ );
+
+ const dialog = await screen.findByRole("dialog", { name: "Fire Maria?" });
+ await within(dialog).findByText(
+ "We couldn't preview what pauses, but you can still fire them.",
+ );
+ const confirm = screen.getByTestId("fire-expert-confirm");
+ expect(confirm.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(confirm);
+
+ await waitFor(() => expect(archiveSpy).toHaveBeenCalled());
+ });
+
+ test("keeps the expert and warns when firing fails", async () => {
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetExpertDetachPreviewMockHandler({
+ schedule_names: [],
+ trigger_names: [],
+ }),
+ getArchiveExpertMockHandler401(),
+ );
+
+ render(<TeamPage />);
+
+ await screen.findByText("Maria");
+ fireEvent.pointerDown(screen.getByTestId("expert-card-actions"), {
+ button: 0,
+ });
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: /Fire Maria/ }),
+ );
+ const confirm = await screen.findByTestId("fire-expert-confirm");
+ await waitFor(() => expect(confirm.hasAttribute("disabled")).toBe(false));
+ fireEvent.click(confirm);
+
+ await waitFor(() =>
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Could not fire Maria",
+ description: "Maria is still on your team. Please try again.",
+ variant: "destructive",
+ }),
+ ),
+ );
+ expect(screen.getByText("Maria")).toBeDefined();
+ });
+
test("shows empty state linking to the marketplace when no experts are hired", async () => {
server.use(getListExpertsMockHandler([]));
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx
index b1d18ea413..d116abb7be 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx
@@ -19,6 +19,8 @@ import {
getScheduleCountLabel,
getWeeklySpend,
} from "../../helpers";
+import { FireExpertDialog } from "../FireExpertDialog/FireExpertDialog";
+import { FireExpertMenu } from "../FireExpertMenu/FireExpertMenu";
import { useExpertTeamCard } from "./useExpertTeamCard";
interface Props {
@@ -38,7 +40,8 @@ export function ExpertTeamCard({
const needsSetupCount = getNeedsSetupCount(expert);
const scheduleLabel = getScheduleCountLabel(schedules);
const weeklySpend = getWeeklySpend(expert);
- const { handleResume, isResuming } = useExpertTeamCard(expert.id);
+ const { handleResume, isResuming, isFireOpen, openFire, closeFire } =
+ useExpertTeamCard(expert.id);
const isPaused = Boolean(expert.schedules_paused_at);
function handleInstallClick() {
@@ -51,11 +54,19 @@ export function ExpertTeamCard({
}
return (
- <div className="flex flex-col gap-3 rounded-2xl border border-zinc-200 bg-white p-5 transition-all duration-200 hover:-translate-y-0.5 hover:border-zinc-300 hover:shadow-[0_16px_40px_-16px_rgba(16,24,40,0.18)]">
+ <div className="relative flex flex-col gap-3 rounded-2xl border border-zinc-200 bg-white p-5 transition-[transform,border-color,box-shadow] duration-200 hover:-translate-y-0.5 hover:border-zinc-300 hover:shadow-[0_16px_40px_-16px_rgba(16,24,40,0.18)]">
+ <div className="absolute right-3 top-3 z-10">
+ <FireExpertMenu
+ expertName={expert.name}
+ onFire={openFire}
+ testId="expert-card-actions"
+ triggerClassName="text-zinc-500 hover:bg-zinc-100 hover:text-zinc-700"
+ />
+ </div>
<Link
href={`/team/${expert.id}`}
aria-label={`View ${expert.name}`}
- className="flex flex-col gap-3"
+ className="flex flex-col gap-3 pr-8"
>
<div className="flex items-center gap-3">
<Avatar className="h-12 w-12">
@@ -146,6 +157,12 @@ export function ExpertTeamCard({
Install workflow
</Button>
</div>
+ <FireExpertDialog
+ expertId={expert.id}
+ expertName={expert.name}
+ open={isFireOpen}
+ onClose={closeFire}
+ />
</div>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/useExpertTeamCard.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/useExpertTeamCard.ts
index 54ac13e2f8..a5e8e8ab4f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/useExpertTeamCard.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/useExpertTeamCard.ts
@@ -4,10 +4,12 @@ import {
} from "@/app/api/__generated__/endpoints/experts/experts";
import { useToast } from "@/components/molecules/Toast/use-toast";
import { useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
export function useExpertTeamCard(expertId: string) {
const queryClient = useQueryClient();
const { toast } = useToast();
+ const [isFireOpen, setIsFireOpen] = useState(false);
const { mutate: resumeSchedules, isPending: isResuming } =
useResumeExpertSchedules({
mutation: {
@@ -29,5 +31,19 @@ export function useExpertTeamCard(expertId: string) {
resumeSchedules({ expertId });
}
- return { handleResume, isResuming };
+ function openFire() {
+ setIsFireOpen(true);
+ }
+
+ function closeFire() {
+ setIsFireOpen(false);
+ }
+
+ return {
+ handleResume,
+ isResuming,
+ isFireOpen,
+ openFire,
+ closeFire,
+ };
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/FireExpertDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/FireExpertDialog.tsx
new file mode 100644
index 0000000000..6f944a90f5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/FireExpertDialog.tsx
@@ -0,0 +1,78 @@
+"use client";
+
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { getFireSummary } from "./helpers";
+import {
+ FireExpertFooter,
+ FireExpertPreview,
+} from "./FireExpertDialogSections";
+import { useFireExpertDialog } from "./useFireExpertDialog";
+
+type Props = {
+ expertId: string;
+ expertName: string;
+ open: boolean;
+ onClose: () => void;
+ onFired?: () => void;
+};
+
+export function FireExpertDialog({
+ expertId,
+ expertName,
+ open,
+ onClose,
+ onFired,
+}: Props) {
+ const {
+ preview,
+ isPreviewLoading,
+ isPreviewError,
+ isPreviewReady,
+ retryPreview,
+ isFiring,
+ handleFire,
+ } = useFireExpertDialog({
+ expertId,
+ expertName,
+ open,
+ onClose,
+ onFired,
+ });
+ const summary = getFireSummary(preview);
+
+ // Match the disabled "Keep" button: while the archive request is in flight
+ // ESC and overlay clicks must not dismiss either, or the user loses the
+ // pending/success/failure feedback for a destructive action.
+ function handleOpenChange(nextOpen: boolean) {
+ if (!nextOpen && !isFiring) onClose();
+ }
+
+ return (
+ <Dialog
+ controlled={{ isOpen: open, set: handleOpenChange }}
+ styling={{ maxWidth: "30rem" }}
+ title={`Fire ${expertName}?`}
+ >
+ <Dialog.Content>
+ <div className="flex flex-col gap-4">
+ <FireExpertPreview
+ expertName={expertName}
+ automationLine={summary.automationLine}
+ items={summary.items}
+ isLoading={isPreviewLoading}
+ isError={isPreviewError}
+ isReady={isPreviewReady}
+ onRetry={retryPreview}
+ />
+ <FireExpertFooter
+ expertName={expertName}
+ isFiring={isFiring}
+ isPreviewLoading={isPreviewLoading}
+ onClose={onClose}
+ onFire={handleFire}
+ />
+ </div>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/FireExpertDialogSections.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/FireExpertDialogSections.tsx
new file mode 100644
index 0000000000..1f10c24b43
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/FireExpertDialogSections.tsx
@@ -0,0 +1,135 @@
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import type { ReactNode } from "react";
+import type { PauseItem } from "./helpers";
+
+type PreviewProps = {
+ expertName: string;
+ automationLine: string;
+ items: PauseItem[];
+ isLoading: boolean;
+ isError: boolean;
+ isReady: boolean;
+ onRetry: () => unknown;
+};
+
+type FooterProps = {
+ expertName: string;
+ isFiring: boolean;
+ isPreviewLoading: boolean;
+ onClose: () => void;
+ onFire: () => void;
+};
+
+type PauseItemsPanelProps = {
+ items: PauseItem[];
+};
+
+type FireLineProps = {
+ children: ReactNode;
+};
+
+export function FireExpertPreview({
+ expertName,
+ automationLine,
+ items,
+ isLoading,
+ isError,
+ isReady,
+ onRetry,
+}: PreviewProps) {
+ function getAutomationLineText() {
+ if (isLoading) return "Checking what will pause…";
+ if (isError)
+ return "We couldn't preview what pauses, but you can still fire them.";
+ return automationLine;
+ }
+
+ function handleRetry() {
+ void onRetry();
+ }
+
+ return (
+ <>
+ <Text variant="body" className="text-zinc-600">
+ Here is exactly what happens when you fire {expertName}.
+ </Text>
+ <ul className="flex flex-col gap-2.5">
+ <FireLine>Installed workflows stay in your library.</FireLine>
+ <FireLine>{getAutomationLineText()}</FireLine>
+ <FireLine>Any chat history stays available but read-only.</FireLine>
+ <FireLine>Their work stays yours.</FireLine>
+ </ul>
+ {isError ? (
+ <div className="flex justify-end">
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={handleRetry}
+ data-testid="fire-preview-retry"
+ >
+ Retry preview
+ </Button>
+ </div>
+ ) : null}
+ {isReady && items.length > 0 ? <PauseItemsPanel items={items} /> : null}
+ </>
+ );
+}
+
+function PauseItemsPanel({ items }: PauseItemsPanelProps) {
+ return (
+ <div className="rounded-xl bg-zinc-50 px-3.5 py-3 ring-1 ring-inset ring-zinc-200/80">
+ <Text variant="small" className="text-zinc-500">
+ Pausing now
+ </Text>
+ <ul className="mt-1 flex flex-col gap-0.5">
+ {items.map((item) => (
+ <li key={item.id} className="truncate text-sm text-zinc-700">
+ {item.name}
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
+
+export function FireExpertFooter({
+ expertName,
+ isFiring,
+ isPreviewLoading,
+ onClose,
+ onFire,
+}: FooterProps) {
+ return (
+ <Dialog.Footer>
+ <Button variant="secondary" disabled={isFiring} onClick={onClose}>
+ Keep {expertName}
+ </Button>
+ <Button
+ variant="destructive"
+ loading={isFiring}
+ disabled={isPreviewLoading}
+ onClick={onFire}
+ data-testid="fire-expert-confirm"
+ >
+ Fire {expertName}
+ </Button>
+ </Dialog.Footer>
+ );
+}
+
+function FireLine({ children }: FireLineProps) {
+ return (
+ <li className="flex items-start gap-2.5">
+ <span
+ aria-hidden
+ className="mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-zinc-300"
+ />
+ <Text variant="body" className="text-zinc-700">
+ {children}
+ </Text>
+ </li>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/helpers.test.ts
new file mode 100644
index 0000000000..876ca65b96
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/helpers.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, test } from "vitest";
+import { getAutomationLine, getFireSummary, getPauseItems } from "./helpers";
+
+describe("getAutomationLine", () => {
+ test("reads as a reassurance when nothing pauses", () => {
+ expect(getAutomationLine(0)).toBe("No automations will pause.");
+ });
+
+ test("uses the singular form for one automation", () => {
+ expect(getAutomationLine(1)).toBe("1 automation will pause.");
+ });
+
+ test("uses the plural form for several automations", () => {
+ expect(getAutomationLine(3)).toBe("3 automations will pause.");
+ });
+});
+
+describe("getPauseItems", () => {
+ test("returns an empty list without a preview", () => {
+ expect(getPauseItems(null)).toEqual([]);
+ });
+
+ test("merges schedules and triggers with type-unique keys", () => {
+ expect(
+ getPauseItems({
+ schedule_names: ["Content Calendar"],
+ trigger_names: ["Inbox watcher"],
+ }),
+ ).toEqual([
+ { id: "schedule-0", name: "Content Calendar" },
+ { id: "trigger-0", name: "Inbox watcher" },
+ ]);
+ });
+
+ test("keeps keys unique when a schedule and trigger share a name", () => {
+ const items = getPauseItems({
+ schedule_names: ["Daily digest"],
+ trigger_names: ["Daily digest"],
+ });
+ const keys = items.map((item) => item.id);
+ expect(new Set(keys).size).toBe(keys.length);
+ });
+});
+
+describe("getFireSummary", () => {
+ test("counts schedules and triggers together as automations", () => {
+ const summary = getFireSummary({
+ schedule_names: ["Content Calendar", "SEO Audit"],
+ trigger_names: ["Inbox watcher"],
+ });
+ expect(summary.items.map((item) => item.name)).toEqual([
+ "Content Calendar",
+ "SEO Audit",
+ "Inbox watcher",
+ ]);
+ expect(summary.automationLine).toBe("3 automations will pause.");
+ });
+
+ test("falls back to the reassuring line without a preview", () => {
+ expect(getFireSummary(null)).toEqual({
+ items: [],
+ automationLine: "No automations will pause.",
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/helpers.ts
new file mode 100644
index 0000000000..fc4a199ec1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/helpers.ts
@@ -0,0 +1,34 @@
+import { ExpertDetachPreview } from "@/app/api/__generated__/models/expertDetachPreview";
+
+export interface PauseItem {
+ id: string;
+ name: string;
+}
+
+export function getPauseItems(
+ preview: ExpertDetachPreview | null,
+): PauseItem[] {
+ if (!preview) return [];
+ // Type-prefixed ids keep list keys unique even when a schedule and a trigger
+ // happen to share the same display name.
+ return [
+ ...preview.schedule_names.map((name, index) => ({
+ id: `schedule-${index}`,
+ name,
+ })),
+ ...preview.trigger_names.map((name, index) => ({
+ id: `trigger-${index}`,
+ name,
+ })),
+ ];
+}
+
+export function getAutomationLine(count: number) {
+ if (count === 0) return "No automations will pause.";
+ return `${count} ${count === 1 ? "automation" : "automations"} will pause.`;
+}
+
+export function getFireSummary(preview: ExpertDetachPreview | null) {
+ const items = getPauseItems(preview);
+ return { items, automationLine: getAutomationLine(items.length) };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/useFireExpertDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/useFireExpertDialog.test.tsx
new file mode 100644
index 0000000000..bdfce67ffe
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/useFireExpertDialog.test.tsx
@@ -0,0 +1,175 @@
+import {
+ getGetExpertQueryKey,
+ getListExpertIdentitiesQueryKey,
+} from "@/app/api/__generated__/endpoints/experts/experts";
+import { getGetHomeDashboardQueryKey } from "@/app/api/__generated__/endpoints/home/home";
+import {
+ getArchiveExpertMockHandler,
+ getGetExpertDetachPreviewMockHandler,
+} from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import { getGetV1ListExecutionSchedulesForAUserQueryKey } from "@/app/api/__generated__/endpoints/schedules/schedules";
+import { server } from "@/mocks/mock-server";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import type { ReactNode } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { useFireExpertDialog } from "./useFireExpertDialog";
+
+type Props = {
+ children: ReactNode;
+};
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ toast: vi.fn(),
+ useToast: () => ({ toast: vi.fn(), dismiss: vi.fn() }),
+}));
+
+function makeClient() {
+ return new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+}
+
+function makeWrapper(client: QueryClient) {
+ return function Wrapper({ children }: Props) {
+ return (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ };
+}
+
+function containsKey(calls: unknown[][], key: readonly unknown[]) {
+ return calls.some(([arg]) => {
+ const queryKey = (arg as { queryKey?: unknown })?.queryKey;
+ return JSON.stringify(queryKey) === JSON.stringify(key);
+ });
+}
+
+describe("useFireExpertDialog invalidation", () => {
+ it("invalidates roster, per-expert, home and schedule caches on a successful fire", async () => {
+ server.use(
+ getGetExpertDetachPreviewMockHandler({
+ schedule_names: [],
+ trigger_names: [],
+ }),
+ getArchiveExpertMockHandler(),
+ );
+
+ const client = makeClient();
+ const invalidateSpy = vi.spyOn(client, "invalidateQueries");
+ const onFired = vi.fn();
+
+ const { result } = renderHook(
+ () =>
+ useFireExpertDialog({
+ expertId: "expert-maria",
+ expertName: "Maria",
+ open: true,
+ onClose: vi.fn(),
+ onFired,
+ }),
+ { wrapper: makeWrapper(client) },
+ );
+
+ await waitFor(() => expect(result.current.isPreviewReady).toBe(true));
+
+ act(() => result.current.handleFire());
+
+ await waitFor(() => expect(onFired).toHaveBeenCalled());
+
+ const calls = invalidateSpy.mock.calls;
+ expect(containsKey(calls, ["/api/experts"])).toBe(true);
+ expect(containsKey(calls, getListExpertIdentitiesQueryKey())).toBe(true);
+ expect(containsKey(calls, getGetExpertQueryKey("expert-maria"))).toBe(true);
+ expect(containsKey(calls, getGetHomeDashboardQueryKey())).toBe(true);
+ expect(
+ containsKey(calls, getGetV1ListExecutionSchedulesForAUserQueryKey()),
+ ).toBe(true);
+ expect(containsKey(calls, ["/api/library/agents"])).toBe(true);
+ });
+
+ it("does not fire before the preview has resolved", async () => {
+ const archiveSpy = vi.fn();
+ server.use(
+ getGetExpertDetachPreviewMockHandler({
+ schedule_names: [],
+ trigger_names: [],
+ }),
+ getArchiveExpertMockHandler(archiveSpy),
+ );
+
+ const client = makeClient();
+ const { result } = renderHook(
+ () =>
+ useFireExpertDialog({
+ expertId: "expert-maria",
+ expertName: "Maria",
+ open: true,
+ onClose: vi.fn(),
+ }),
+ { wrapper: makeWrapper(client) },
+ );
+
+ // Preview not yet ready on first render — a click must be a no-op.
+ expect(result.current.isPreviewReady).toBe(false);
+ act(() => result.current.handleFire());
+ expect(archiveSpy).not.toHaveBeenCalled();
+ });
+
+ it("does not fire while a cached preview is being retried", async () => {
+ const archiveSpy = vi.fn();
+ server.use(
+ getGetExpertDetachPreviewMockHandler({
+ schedule_names: ["Weekly report"],
+ trigger_names: [],
+ }),
+ getArchiveExpertMockHandler(archiveSpy),
+ );
+
+ const client = makeClient();
+ const { result } = renderHook(
+ () =>
+ useFireExpertDialog({
+ expertId: "expert-maria",
+ expertName: "Maria",
+ open: true,
+ onClose: vi.fn(),
+ }),
+ { wrapper: makeWrapper(client) },
+ );
+ await waitFor(() => expect(result.current.isPreviewReady).toBe(true));
+
+ let releaseRetry: () => void = () => undefined;
+ const retryGate = new Promise<void>((resolve) => {
+ releaseRetry = resolve;
+ });
+ server.use(
+ http.get("*/api/experts/:expertId/detach-preview", async () => {
+ await retryGate;
+ return HttpResponse.json({
+ schedule_names: ["Weekly report"],
+ trigger_names: [],
+ });
+ }),
+ );
+
+ let retryPromise: Promise<unknown> | undefined;
+ act(() => {
+ retryPromise = result.current.retryPreview();
+ });
+ await waitFor(() => expect(result.current.isPreviewLoading).toBe(true));
+
+ act(() => result.current.handleFire());
+ expect(archiveSpy).not.toHaveBeenCalled();
+
+ await act(async () => {
+ releaseRetry();
+ await retryPromise;
+ });
+ await waitFor(() => expect(result.current.isPreviewLoading).toBe(false));
+
+ act(() => result.current.handleFire());
+ await waitFor(() => expect(archiveSpy).toHaveBeenCalledTimes(1));
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/useFireExpertDialog.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/useFireExpertDialog.ts
new file mode 100644
index 0000000000..4c1f99ed70
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/useFireExpertDialog.ts
@@ -0,0 +1,81 @@
+import { getGetHomeDashboardQueryKey } from "@/app/api/__generated__/endpoints/home/home";
+import {
+ getGetExpertQueryKey,
+ useArchiveExpert,
+ useGetExpertDetachPreview,
+} from "@/app/api/__generated__/endpoints/experts/experts";
+import { okData } from "@/app/api/helpers";
+import { toast } from "@/components/molecules/Toast/use-toast";
+import { invalidateExpertRosterQueries } from "@/services/experts/invalidate-experts";
+import { invalidateAllScheduleQueries } from "@/services/schedules/invalidate-schedules";
+import { useQueryClient } from "@tanstack/react-query";
+
+interface Args {
+ expertId: string;
+ expertName: string;
+ open: boolean;
+ onClose: () => void;
+ onFired?: () => void;
+}
+
+export function useFireExpertDialog({
+ expertId,
+ expertName,
+ open,
+ onClose,
+ onFired,
+}: Args) {
+ const queryClient = useQueryClient();
+
+ const previewQuery = useGetExpertDetachPreview(expertId, {
+ query: { enabled: open, select: (res) => okData(res) ?? null },
+ });
+
+ const { mutate, isPending: isFiring } = useArchiveExpert({
+ mutation: {
+ onSuccess: async () => {
+ await Promise.all([
+ invalidateExpertRosterQueries(queryClient),
+ queryClient.invalidateQueries({
+ queryKey: getGetExpertQueryKey(expertId),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: getGetHomeDashboardQueryKey(),
+ }),
+ invalidateAllScheduleQueries(queryClient),
+ ]);
+ toast({
+ title: `${expertName} was fired`,
+ description: `You can re-hire ${expertName} anytime from the marketplace.`,
+ });
+ onClose();
+ onFired?.();
+ },
+ onError: () => {
+ toast({
+ title: `Could not fire ${expertName}`,
+ description: `${expertName} is still on your team. Please try again.`,
+ variant: "destructive",
+ });
+ },
+ },
+ });
+
+ function handleFire() {
+ // Any in-flight preview blocks firing, including a manual retry with
+ // cached data. A failed, settled preview remains informational and does
+ // not hard-block the destructive action.
+ if (previewQuery.isFetching) return;
+ mutate({ expertId });
+ }
+
+ return {
+ preview: previewQuery.data ?? null,
+ isPreviewLoading: previewQuery.isFetching,
+ isPreviewError: previewQuery.isError,
+ isPreviewReady: previewQuery.isSuccess,
+ retryPreview: previewQuery.refetch,
+ isFiring,
+ handleFire,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertMenu/FireExpertMenu.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertMenu/FireExpertMenu.tsx
new file mode 100644
index 0000000000..7e41950d00
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertMenu/FireExpertMenu.tsx
@@ -0,0 +1,51 @@
+import { Icon } from "@/components/atoms/Icon/Icon";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/molecules/DropdownMenu/DropdownMenu";
+import { cn } from "@/lib/utils";
+import { Logout03Icon, MoreVerticalIcon } from "@hugeicons/core-free-icons";
+
+interface Props {
+ expertName: string;
+ onFire: () => void;
+ testId: string;
+ triggerClassName?: string;
+}
+
+export function FireExpertMenu({
+ expertName,
+ onFire,
+ testId,
+ triggerClassName,
+}: Props) {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={`${expertName} actions`}
+ data-testid={testId}
+ onClick={(event) => event.stopPropagation()}
+ className={cn(
+ "inline-flex h-9 w-9 items-center justify-center rounded-full transition-colors",
+ triggerClassName,
+ )}
+ >
+ <Icon icon={MoreVerticalIcon} size={18} />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" sideOffset={6}>
+ <DropdownMenuItem
+ onSelect={onFire}
+ className="flex cursor-pointer items-center gap-2 text-red-600 focus:bg-red-50 focus:text-red-700"
+ >
+ <Icon icon={Logout03Icon} size={14} />
+ Fire {expertName}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/SoulDrawer/useSoulDrawer.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/SoulDrawer/useSoulDrawer.ts
index 53ac92ba6b..2bde6b8d59 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/SoulDrawer/useSoulDrawer.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/SoulDrawer/useSoulDrawer.ts
@@ -1,11 +1,11 @@
import {
getGetExpertQueryKey,
- getListExpertsQueryKey,
useUpdateExpertSoul,
} from "@/app/api/__generated__/endpoints/experts/experts";
import { Expert } from "@/app/api/__generated__/models/expert";
import { ExpertSoulUpdate } from "@/app/api/__generated__/models/expertSoulUpdate";
import { toast } from "@/components/molecules/Toast/use-toast";
+import { invalidateExpertRosterQueries } from "@/services/experts/invalidate-experts";
import { useQueryClient } from "@tanstack/react-query";
import { FormEvent, useState } from "react";
@@ -39,7 +39,7 @@ export function useSoulDrawer({ expert, onClose }: Args) {
try {
await updateSoul({ expertId: expert.id, data: soul });
await Promise.all([
- queryClient.invalidateQueries({ queryKey: getListExpertsQueryKey() }),
+ invalidateExpertRosterQueries(queryClient),
queryClient.invalidateQueries({
queryKey: getGetExpertQueryKey(expert.id),
}),
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index a8415d3e96..25dee44d55 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -5469,6 +5469,7 @@
"get": {
"tags": ["v2", "experts", "experts", "private"],
"summary": "List Experts",
+ "description": "List the user's active hired experts.",
"operationId": "list_experts",
"responses": {
"200": {
@@ -5526,6 +5527,32 @@
"security": [{ "HTTPBearerJWT": [] }]
}
},
+ "/api/experts/identities": {
+ "get": {
+ "tags": ["v2", "experts", "experts", "private"],
+ "summary": "List Expert Identities",
+ "description": "List the lightweight active and archived identity projection for chat.",
+ "operationId": "list_expert_identities",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "items": { "$ref": "#/components/schemas/ExpertIdentity" },
+ "type": "array",
+ "title": "Response List Expert Identities"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
"/api/experts/templates": {
"get": {
"tags": ["v2", "experts", "experts", "private"],
@@ -17796,6 +17823,21 @@
"title": "ExpertDetachPreview",
"description": "What archiving the expert would pause — drives the confirm dialog."
},
+ "ExpertIdentity": {
+ "properties": {
+ "id": { "type": "string", "title": "Id" },
+ "name": { "type": "string", "title": "Name" },
+ "avatar_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Avatar Url"
+ },
+ "role": { "type": "string", "title": "Role" },
+ "is_archived": { "type": "boolean", "title": "Is Archived" }
+ },
+ "type": "object",
+ "required": ["id", "name", "avatar_url", "role", "is_archived"],
+ "title": "ExpertIdentity"
+ },
"ExpertSoulUpdate": {
"properties": {
"name": {
diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/expert-groups.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/expert-groups.test.tsx
index a7ec72e0a4..90d97096a9 100644
--- a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/expert-groups.test.tsx
+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/expert-groups.test.tsx
@@ -1,5 +1,5 @@
import { getGetV2ListSessionsMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";
-import { getListExpertsMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import { getListExpertIdentitiesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
import type { Expert } from "@/app/api/__generated__/models/expert";
import { SESSION_LIST_REFETCH_INTERVAL_MS } from "@/app/(platform)/copilot/useSessionList";
import { SidebarProvider } from "@/components/ui/sidebar";
@@ -91,7 +91,7 @@ describe("RecentChats — expert groups", () => {
const sessions = makeSessions(2);
server.use(
getGetV2ListSessionsMockHandler200({ sessions, total: sessions.length }),
- getListExpertsMockHandler([]),
+ getListExpertIdentitiesMockHandler([]),
);
renderRecentChats();
@@ -109,7 +109,7 @@ describe("RecentChats — expert groups", () => {
const sessions = makeSessions(14);
server.use(
getGetV2ListSessionsMockHandler200({ sessions, total: sessions.length }),
- getListExpertsMockHandler([]),
+ getListExpertIdentitiesMockHandler([]),
);
renderRecentChats();
@@ -134,7 +134,7 @@ describe("RecentChats — expert groups", () => {
const sessions = [...makeSessions(8), ...makeSessions(7, mariaExpert.id)];
server.use(
getGetV2ListSessionsMockHandler200({ sessions, total: sessions.length }),
- getListExpertsMockHandler([mariaExpert]),
+ getListExpertIdentitiesMockHandler([mariaExpert]),
);
renderRecentChats();
@@ -160,7 +160,7 @@ describe("RecentChats — expert groups", () => {
const sessions = makeSessions(2, "expert-ghost");
server.use(
getGetV2ListSessionsMockHandler200({ sessions, total: sessions.length }),
- getListExpertsMockHandler([]),
+ getListExpertIdentitiesMockHandler([]),
);
renderRecentChats();
@@ -177,7 +177,7 @@ describe("RecentChats — expert groups", () => {
sessions,
total: sessions.length + 10,
}),
- getListExpertsMockHandler([]),
+ getListExpertIdentitiesMockHandler([]),
);
renderRecentChats();
@@ -195,7 +195,7 @@ describe("RecentChats — expert groups", () => {
listCalls++;
return HttpResponse.json({ sessions, total: sessions.length });
}),
- getListExpertsMockHandler([mariaExpert]),
+ getListExpertIdentitiesMockHandler([mariaExpert]),
);
renderRecentChats();
diff --git a/autogpt_platform/frontend/src/services/experts/invalidate-experts.test.ts b/autogpt_platform/frontend/src/services/experts/invalidate-experts.test.ts
new file mode 100644
index 0000000000..1f5d25548d
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/experts/invalidate-experts.test.ts
@@ -0,0 +1,23 @@
+import {
+ getListExpertIdentitiesQueryKey,
+ getListExpertsQueryKey,
+} from "@/app/api/__generated__/endpoints/experts/experts";
+import { QueryClient } from "@tanstack/react-query";
+import { describe, expect, it, vi } from "vitest";
+import { invalidateExpertRosterQueries } from "./invalidate-experts";
+
+describe("invalidateExpertRosterQueries", () => {
+ it("invalidates both the full roster and chat identity projection", async () => {
+ const queryClient = new QueryClient();
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");
+
+ await invalidateExpertRosterQueries(queryClient);
+
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: getListExpertsQueryKey(),
+ });
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: getListExpertIdentitiesQueryKey(),
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/experts/invalidate-experts.ts b/autogpt_platform/frontend/src/services/experts/invalidate-experts.ts
new file mode 100644
index 0000000000..65a779716e
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/experts/invalidate-experts.ts
@@ -0,0 +1,14 @@
+import {
+ getListExpertIdentitiesQueryKey,
+ getListExpertsQueryKey,
+} from "@/app/api/__generated__/endpoints/experts/experts";
+import type { QueryClient } from "@tanstack/react-query";
+
+export function invalidateExpertRosterQueries(queryClient: QueryClient) {
+ return Promise.all([
+ queryClient.invalidateQueries({ queryKey: getListExpertsQueryKey() }),
+ queryClient.invalidateQueries({
+ queryKey: getListExpertIdentitiesQueryKey(),
+ }),
+ ]);
+}
diff --git a/autogpt_platform/frontend/src/services/schedules/invalidate-schedules.ts b/autogpt_platform/frontend/src/services/schedules/invalidate-schedules.ts
index 56c73f77fe..0017d5527d 100644
--- a/autogpt_platform/frontend/src/services/schedules/invalidate-schedules.ts
+++ b/autogpt_platform/frontend/src/services/schedules/invalidate-schedules.ts
@@ -26,21 +26,26 @@ export function invalidateAllScheduleQueries(
queryClient: QueryClient,
graphId?: string,
) {
- queryClient.invalidateQueries({
- queryKey: getGetV1ListExecutionSchedulesForAUserQueryKey(),
- });
- queryClient.invalidateQueries({
- queryKey: getListCopilotFollowupSchedulesQueryKey(),
- });
- // Partial-key match: hits every variant of the library agents query
- // (search, filter, pagination, plus the infinite-query form used by
- // `/library`'s agent list). Required so `agent.is_scheduled` —
- // computed server-side and fed into the fleet-summary "Scheduled"
- // count — refreshes after a schedule mutation.
- queryClient.invalidateQueries({ queryKey: ["/api/library/agents"] });
- if (graphId) {
+ const invalidations = [
+ queryClient.invalidateQueries({
+ queryKey: getGetV1ListExecutionSchedulesForAUserQueryKey(),
+ }),
queryClient.invalidateQueries({
- queryKey: getGetV1ListExecutionSchedulesForAGraphQueryKey(graphId),
- });
+ queryKey: getListCopilotFollowupSchedulesQueryKey(),
+ }),
+ // Partial-key match: hits every variant of the library agents query
+ // (search, filter, pagination, plus the infinite-query form used by
+ // `/library`'s agent list). Required so `agent.is_scheduled` —
+ // computed server-side and fed into the fleet-summary "Scheduled"
+ // count — refreshes after a schedule mutation.
+ queryClient.invalidateQueries({ queryKey: ["/api/library/agents"] }),
+ ];
+ if (graphId) {
+ invalidations.push(
+ queryClient.invalidateQueries({
+ queryKey: getGetV1ListExecutionSchedulesForAGraphQueryKey(graphId),
+ }),
+ );
}
+ return Promise.all(invalidations);
}