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): user-facing memory settings page (#14071)

Nicholas Tindle7b847b6699ea
diff --git a/autogpt_platform/backend/backend/api/features/memory/__init__.py b/autogpt_platform/backend/backend/api/features/memory/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/api/features/memory/models.py b/autogpt_platform/backend/backend/api/features/memory/models.py
new file mode 100644
index 0000000000..be62eb679c
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/memory/models.py
@@ -0,0 +1,43 @@
+"""Response models for the user-facing memory API (settings page)."""
+
+from pydantic import BaseModel
+
+
+class MemoryScopeOverview(BaseModel):
+ """Counts for one memory scope, shown on the settings page and in the
+ erase-confirmation dialog."""
+
+ expert_id: str | None = None
+ facts: int
+ entities: int
+ episodes: int
+
+
+class MemoryFact(BaseModel):
+ """One live fact edge, as shown in the recent-memories list."""
+
+ uuid: str
+ fact: str | None = None
+ name: str | None = None
+ source: str
+ target: str
+ created_at: str | None = None
+
+
+class MemoryFactListResponse(BaseModel):
+ expert_id: str | None = None
+ items: list[MemoryFact]
+
+
+class ForgetFactResponse(BaseModel):
+ uuid: str
+ forgotten: bool
+
+
+class EraseMemoryResponse(BaseModel):
+ """Result of a scope wipe. ``deleted_nodes`` counts every node removed —
+ entities, episodes (raw text included), and communities."""
+
+ expert_id: str | None = None
+ deleted_nodes: int
+ erased: bool
diff --git a/autogpt_platform/backend/backend/api/features/memory/routes.py b/autogpt_platform/backend/backend/api/features/memory/routes.py
new file mode 100644
index 0000000000..fe755f28a1
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/memory/routes.py
@@ -0,0 +1,315 @@
+"""User-facing memory API: read + forget for the caller's own memory scopes.
+
+Backs the Settings → Memory page (SECRT-2580). Scope is structural, mirroring
+the admin memory API: account (AutoPilot) routes live at ``/memory/...`` and
+expert routes at ``/memory/experts/{expert_id}/...``. Every route resolves the
+scope from the *authenticated caller* — there is no target-user path segment,
+so these routes can never read or delete another user's memory by construction.
+
+Deletion semantics match the chat forget tool: single-fact forget is a
+bi-temporal system retraction (sets only ``expired_at``; the edge stops being
+served but stays for audit), while the scope erase hard-deletes every node and
+edge in the scope's graph, raw episode text included.
+"""
+
+import logging
+from datetime import datetime, timezone
+from typing import Annotated
+
+import autogpt_libs.auth as autogpt_auth_lib
+from fastapi import APIRouter, HTTPException, Path, Query, Security
+from redis.exceptions import ResponseError
+
+from backend.api.features.experts import experts_db
+from backend.api.features.memory.models import (
+ EraseMemoryResponse,
+ ForgetFactResponse,
+ MemoryFact,
+ MemoryFactListResponse,
+ MemoryScopeOverview,
+)
+from backend.copilot.graphiti.client import derive_memory_group_id
+from backend.copilot.graphiti.config import graphiti_config, is_enabled_for_user
+from backend.copilot.graphiti.falkordb_driver import AutoGPTFalkorDriver
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(
+ prefix="/memory",
+ tags=["memory", "private"],
+ dependencies=[Security(autogpt_auth_lib.requires_user)],
+)
+
+_EXPERT_ID_PATH = Path(
+ min_length=1, max_length=128, description="Expert id owned by the caller"
+)
+_FACT_UUID_PATH = Path(min_length=1, max_length=128, description="Fact edge uuid")
+_LIMIT_QUERY = Query(ge=1, le=500)
+
+_MISSING_GRAPH_MARKERS = ("no such graph", "does not exist", "invalid graph")
+
+
+def _now_iso() -> str:
+ """FalkorDB has no Cypher ``datetime()``; timestamps are bound in Python."""
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _is_missing_graph_error(exc: BaseException) -> bool:
+ if not isinstance(exc, ResponseError):
+ return False
+ msg = str(exc).lower()
+ return any(marker in msg for marker in _MISSING_GRAPH_MARKERS)
+
+
+def _open_driver(group_id: str) -> AutoGPTFalkorDriver:
+ """Cypher-only driver — skips LLM-client construction and the per-init
+ index build (indices exist from the long-lived chat-write client)."""
+ return AutoGPTFalkorDriver(
+ host=graphiti_config.falkordb_host,
+ port=graphiti_config.falkordb_port,
+ password=graphiti_config.falkordb_password or None,
+ database=group_id,
+ build_indices=False,
+ )
+
+
+async def _resolve_scope(user_id: str, expert_id: str | None) -> tuple[str, str | None]:
+ """Resolve the caller-owned memory group for the requested scope.
+
+ Memory must be enabled for the caller, and an expert scope must name an
+ active expert the caller owns — archived experts 404 here, matching the
+ settings page's active-experts-only dropdown.
+ """
+ if not await is_enabled_for_user(user_id):
+ raise HTTPException(
+ status_code=403, detail="Memory is not enabled for your account"
+ )
+
+ if expert_id is None:
+ try:
+ return derive_memory_group_id(user_id), None
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc))
+
+ expert = await experts_db.get_expert(user_id, expert_id, include_workflows=False)
+ if expert is None:
+ raise HTTPException(status_code=404, detail="Expert not found")
+
+ try:
+ return derive_memory_group_id(user_id, expert.id), expert.id
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc))
+
+
+async def _count(driver: AutoGPTFalkorDriver, query: str) -> int:
+ try:
+ result = await driver.execute_query(query)
+ rows = result[0] if result else []
+ return int(rows[0]["c"]) if rows else 0
+ except ResponseError as exc:
+ if _is_missing_graph_error(exc):
+ return 0
+ raise
+
+
+async def _get_overview_impl(
+ user_id: str, expert_id: str | None
+) -> MemoryScopeOverview:
+ group_id, resolved_expert_id = await _resolve_scope(user_id, expert_id)
+ driver = _open_driver(group_id)
+ try:
+ facts = await _count(
+ driver,
+ "MATCH ()-[e:RELATES_TO]->() WHERE e.expired_at IS NULL "
+ "RETURN count(e) AS c",
+ )
+ entities = await _count(driver, "MATCH (n:Entity) RETURN count(n) AS c")
+ episodes = await _count(driver, "MATCH (n:Episodic) RETURN count(n) AS c")
+ finally:
+ await driver.close()
+ return MemoryScopeOverview(
+ expert_id=resolved_expert_id,
+ facts=facts,
+ entities=entities,
+ episodes=episodes,
+ )
+
+
[email protected]("/overview", operation_id="get_my_memory_overview")
+async def get_my_memory_overview(
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> MemoryScopeOverview:
+ """Counts for the caller's account (AutoPilot) memory."""
+ return await _get_overview_impl(user_id, None)
+
+
+ "/experts/{expert_id}/overview", operation_id="get_my_expert_memory_overview"
+)
+async def get_my_expert_memory_overview(
+ expert_id: Annotated[str, _EXPERT_ID_PATH],
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> MemoryScopeOverview:
+ """Counts for one of the caller's experts' isolated memory."""
+ return await _get_overview_impl(user_id, expert_id)
+
+
+async def _list_facts_impl(
+ user_id: str, expert_id: str | None, limit: int
+) -> MemoryFactListResponse:
+ group_id, resolved_expert_id = await _resolve_scope(user_id, expert_id)
+ driver = _open_driver(group_id)
+ try:
+ result = await driver.execute_query(
+ """
+ MATCH (src:Entity)-[e:RELATES_TO]->(tgt:Entity)
+ WHERE e.group_id = $g AND e.expired_at IS NULL
+ RETURN e.uuid AS uuid,
+ e.fact AS fact,
+ e.name AS name,
+ src.name AS source,
+ tgt.name AS target,
+ toString(e.created_at) AS created_at
+ ORDER BY e.created_at DESC
+ LIMIT $limit
+ """,
+ g=group_id,
+ limit=limit,
+ )
+ rows = result[0] if result else []
+ except ResponseError as exc:
+ if not _is_missing_graph_error(exc):
+ raise
+ rows = []
+ finally:
+ await driver.close()
+
+ items = [
+ MemoryFact(
+ uuid=str(r.get("uuid", "")),
+ fact=r.get("fact"),
+ name=r.get("name"),
+ source=str(r.get("source") or ""),
+ target=str(r.get("target") or ""),
+ created_at=r.get("created_at"),
+ )
+ for r in rows
+ ]
+ return MemoryFactListResponse(expert_id=resolved_expert_id, items=items)
+
+
[email protected]("/facts", operation_id="list_my_memory_facts")
+async def list_my_memory_facts(
+ limit: Annotated[int, _LIMIT_QUERY] = 50,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> MemoryFactListResponse:
+ """Live facts in the caller's account memory, newest first."""
+ return await _list_facts_impl(user_id, None, limit)
+
+
[email protected]("/experts/{expert_id}/facts", operation_id="list_my_expert_memory_facts")
+async def list_my_expert_memory_facts(
+ expert_id: Annotated[str, _EXPERT_ID_PATH],
+ limit: Annotated[int, _LIMIT_QUERY] = 50,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> MemoryFactListResponse:
+ """Live facts in one expert's isolated memory, newest first."""
+ return await _list_facts_impl(user_id, expert_id, limit)
+
+
+async def _forget_fact_impl(
+ user_id: str, expert_id: str | None, fact_uuid: str
+) -> ForgetFactResponse:
+ group_id, _ = await _resolve_scope(user_id, expert_id)
+ driver = _open_driver(group_id)
+ try:
+ # Same retraction the chat forget tool performs (``expired_at`` only —
+ # a system retraction, not a world change), plus a ``group_id``
+ # predicate as defense-in-depth on top of the per-group database.
+ result = await driver.execute_query(
+ """
+ MATCH ()-[e:MENTIONS|RELATES_TO|HAS_MEMBER
+ {uuid: $uuid, group_id: $g}]->()
+ SET e.expired_at = $now
+ RETURN e.uuid AS uuid
+ """,
+ uuid=fact_uuid,
+ g=group_id,
+ now=_now_iso(),
+ )
+ records = result[0] if result else []
+ except ResponseError as exc:
+ if not _is_missing_graph_error(exc):
+ raise
+ records = []
+ finally:
+ await driver.close()
+
+ if not records:
+ raise HTTPException(status_code=404, detail="Memory not found")
+ return ForgetFactResponse(uuid=fact_uuid, forgotten=True)
+
+
[email protected]("/facts/{fact_uuid}", operation_id="forget_my_memory_fact")
+async def forget_my_memory_fact(
+ fact_uuid: Annotated[str, _FACT_UUID_PATH],
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> ForgetFactResponse:
+ """Forget one fact from the caller's account memory."""
+ return await _forget_fact_impl(user_id, None, fact_uuid)
+
+
+ "/experts/{expert_id}/facts/{fact_uuid}",
+ operation_id="forget_my_expert_memory_fact",
+)
+async def forget_my_expert_memory_fact(
+ expert_id: Annotated[str, _EXPERT_ID_PATH],
+ fact_uuid: Annotated[str, _FACT_UUID_PATH],
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> ForgetFactResponse:
+ """Forget one fact from an expert's isolated memory."""
+ return await _forget_fact_impl(user_id, expert_id, fact_uuid)
+
+
+async def _erase_scope_impl(user_id: str, expert_id: str | None) -> EraseMemoryResponse:
+ group_id, resolved_expert_id = await _resolve_scope(user_id, expert_id)
+ driver = _open_driver(group_id)
+ deleted = 0
+ try:
+ deleted = await _count(driver, "MATCH (n) RETURN count(n) AS c")
+ if deleted:
+ await driver.execute_query("MATCH (n) DETACH DELETE n")
+ except ResponseError as exc:
+ # A missing-graph error here means the graph vanished between the
+ # count and the delete — the scope is gone either way, so keep the
+ # counted value instead of misreporting 0.
+ if not _is_missing_graph_error(exc):
+ raise
+ finally:
+ await driver.close()
+
+ logger.info(
+ f"Memory erase: user {user_id[:12]} wiped scope "
+ f"{resolved_expert_id or 'AutoPilot'} ({deleted} nodes)"
+ )
+ return EraseMemoryResponse(
+ expert_id=resolved_expert_id, deleted_nodes=deleted, erased=True
+ )
+
+
[email protected]("", operation_id="erase_my_memory")
+async def erase_my_memory(
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> EraseMemoryResponse:
+ """Permanently erase the caller's entire account memory."""
+ return await _erase_scope_impl(user_id, None)
+
+
[email protected]("/experts/{expert_id}", operation_id="erase_my_expert_memory")
+async def erase_my_expert_memory(
+ expert_id: Annotated[str, _EXPERT_ID_PATH],
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> EraseMemoryResponse:
+ """Permanently erase one expert's entire isolated memory."""
+ return await _erase_scope_impl(user_id, expert_id)
diff --git a/autogpt_platform/backend/backend/api/features/memory/routes_test.py b/autogpt_platform/backend/backend/api/features/memory/routes_test.py
new file mode 100644
index 0000000000..1d8c1e3869
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/memory/routes_test.py
@@ -0,0 +1,215 @@
+"""Tests for the user-facing memory routes (Settings → Memory)."""
+
+from unittest.mock import AsyncMock, patch
+
+import fastapi
+import fastapi.testclient
+import pytest
+from autogpt_libs.auth.jwt_utils import get_jwt_payload
+from redis.exceptions import ResponseError
+
+from backend.api.features.experts.models import PROTECTED_SOUL_RULES, Expert
+from backend.copilot.graphiti.client import derive_memory_group_id
+
+from .routes import router as memory_router
+
+app = fastapi.FastAPI()
+app.include_router(memory_router)
+
+client = fastapi.testclient.TestClient(app)
+
+_MOCK_MODULE = "backend.api.features.memory.routes"
+
+_EXPERT_ID = "11111111-2222-3333-4444-555555555555"
+
+
[email protected](autouse=True)
+def setup_app_auth(mock_jwt_user):
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
+ yield
+ app.dependency_overrides.clear()
+
+
[email protected](autouse=True)
+def memory_enabled():
+ with patch(
+ f"{_MOCK_MODULE}.is_enabled_for_user", new=AsyncMock(return_value=True)
+ ) as mock:
+ yield mock
+
+
+def _driver_returning(*query_results) -> AsyncMock:
+ driver = AsyncMock()
+ driver.execute_query.side_effect = [(r, None, None) for r in query_results]
+ driver.close = AsyncMock()
+ return driver
+
+
+def _expert(expert_id: str = _EXPERT_ID) -> Expert:
+ return Expert(
+ id=expert_id,
+ name="Maria",
+ avatar_url=None,
+ role="Growth Marketer",
+ tagline=None,
+ bio=None,
+ skills=[],
+ identity="Growth expert.",
+ voice_preferences="",
+ boundaries="",
+ protected_soul_rules=list(PROTECTED_SOUL_RULES),
+ is_template=False,
+ source_template_id=None,
+ is_archived=False,
+ workflows=[],
+ )
+
+
+class TestOverview:
+ def test_returns_scope_counts(self) -> None:
+ driver = _driver_returning([{"c": 12}], [{"c": 34}], [{"c": 5}])
+ with patch(f"{_MOCK_MODULE}._open_driver", return_value=driver):
+ resp = client.get("/memory/overview")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["expert_id"] is None
+ assert body["facts"] == 12
+ assert body["entities"] == 34
+ assert body["episodes"] == 5
+ driver.close.assert_awaited_once()
+
+ def test_disabled_memory_is_403(self, memory_enabled) -> None:
+ memory_enabled.return_value = False
+ resp = client.get("/memory/overview")
+ assert resp.status_code == 403
+
+ def test_fact_count_only_counts_live_edges(self) -> None:
+ driver = _driver_returning([{"c": 0}], [{"c": 0}], [{"c": 0}])
+ with patch(f"{_MOCK_MODULE}._open_driver", return_value=driver):
+ client.get("/memory/overview")
+ fact_query = driver.execute_query.await_args_list[0].args[0]
+ assert "expired_at IS NULL" in fact_query
+
+
+class TestListFacts:
+ def test_maps_rows_to_facts(self) -> None:
+ driver = _driver_returning(
+ [
+ {
+ "uuid": "edge-1",
+ "fact": "Prefers Monday summaries",
+ "name": "prefers",
+ "source": "User",
+ "target": "Monday summaries",
+ "created_at": "2026-08-16T00:00:00Z",
+ }
+ ]
+ )
+ with patch(f"{_MOCK_MODULE}._open_driver", return_value=driver):
+ resp = client.get("/memory/facts?limit=5")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["expert_id"] is None
+ assert body["items"][0]["uuid"] == "edge-1"
+ assert body["items"][0]["fact"] == "Prefers Monday summaries"
+ query = driver.execute_query.await_args_list[0].args[0]
+ assert "expired_at IS NULL" in query
+ assert "ORDER BY e.created_at DESC" in query
+
+ def test_missing_graph_is_empty_list(self) -> None:
+ driver = AsyncMock()
+ driver.execute_query.side_effect = ResponseError("no such graph")
+ driver.close = AsyncMock()
+ with patch(f"{_MOCK_MODULE}._open_driver", return_value=driver):
+ resp = client.get("/memory/facts")
+ assert resp.status_code == 200
+ assert resp.json()["items"] == []
+
+ def test_expert_scope_uses_expert_group(self, test_user_id) -> None:
+ driver = _driver_returning([])
+ opened: list[str] = []
+
+ def open_driver(group_id: str):
+ opened.append(group_id)
+ return driver
+
+ with (
+ patch(f"{_MOCK_MODULE}._open_driver", side_effect=open_driver),
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=_expert()),
+ ) as get_expert,
+ ):
+ resp = client.get(f"/memory/experts/{_EXPERT_ID}/facts")
+ assert resp.status_code == 200
+ assert resp.json()["expert_id"] == _EXPERT_ID
+ assert opened == [derive_memory_group_id(test_user_id, _EXPERT_ID)]
+ get_expert.assert_awaited_once_with(
+ test_user_id, _EXPERT_ID, include_workflows=False
+ )
+
+ def test_unknown_expert_is_404(self) -> None:
+ with patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=None),
+ ):
+ resp = client.get(f"/memory/experts/{_EXPERT_ID}/facts")
+ assert resp.status_code == 404
+
+
+class TestForgetFact:
+ def test_retracts_matching_edge(self) -> None:
+ driver = _driver_returning([{"uuid": "edge-1"}])
+ with patch(f"{_MOCK_MODULE}._open_driver", return_value=driver):
+ resp = client.delete("/memory/facts/edge-1")
+ assert resp.status_code == 200
+ assert resp.json() == {"uuid": "edge-1", "forgotten": True}
+ query = driver.execute_query.await_args_list[0].args[0]
+ assert "SET e.expired_at = $now" in query
+ assert "group_id: $g" in query
+ assert "DELETE" not in query
+
+ def test_no_match_is_404(self) -> None:
+ driver = _driver_returning([])
+ with patch(f"{_MOCK_MODULE}._open_driver", return_value=driver):
+ resp = client.delete("/memory/facts/edge-unknown")
+ assert resp.status_code == 404
+
+
+class TestEraseScope:
+ def test_erases_all_nodes(self) -> None:
+ driver = _driver_returning([{"c": 214}], [])
+ with patch(f"{_MOCK_MODULE}._open_driver", return_value=driver):
+ resp = client.delete("/memory")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["erased"] is True
+ assert body["deleted_nodes"] == 214
+ wipe_query = driver.execute_query.await_args_list[1].args[0]
+ assert "DETACH DELETE" in wipe_query
+
+ def test_empty_scope_never_touches_graph(self) -> None:
+ driver = AsyncMock()
+ driver.execute_query.side_effect = ResponseError("no such graph")
+ driver.close = AsyncMock()
+ with patch(f"{_MOCK_MODULE}._open_driver", return_value=driver):
+ resp = client.delete("/memory")
+ assert resp.status_code == 200
+ assert resp.json()["deleted_nodes"] == 0
+ assert driver.execute_query.await_count == 1
+
+ def test_expert_erase_resolves_ownership(self, test_user_id) -> None:
+ driver = _driver_returning([{"c": 3}], [])
+ with (
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver),
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=_expert()),
+ ) as get_expert,
+ ):
+ resp = client.delete(f"/memory/experts/{_EXPERT_ID}")
+ assert resp.status_code == 200
+ assert resp.json()["expert_id"] == _EXPERT_ID
+ get_expert.assert_awaited_once_with(
+ test_user_id, _EXPERT_ID, include_workflows=False
+ )
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index cf6d73f60e..588414626d 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -38,6 +38,7 @@ import backend.api.features.library.db
import backend.api.features.library.model
import backend.api.features.library.routes
import backend.api.features.mcp.routes as mcp_routes
+import backend.api.features.memory.routes as memory_routes
import backend.api.features.oauth
import backend.api.features.onboarding_dump.routes as onboarding_dump_routes
import backend.api.features.orgs.invitation_routes
@@ -439,6 +440,7 @@ app.include_router(
backend.api.features.library.routes.router, tags=["v2"], prefix="/api/library"
)
app.include_router(experts_routes.router, tags=["v2", "experts"], prefix="/api")
+app.include_router(memory_routes.router, tags=["v2", "memory"], prefix="/api")
app.include_router(home_routes.router, prefix="/api")
app.include_router(
backend.api.features.otto.routes.router, tags=["v2", "otto"], prefix="/api/otto"
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/helpers.ts
index db0a249ef0..a262604757 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/helpers.ts
@@ -1,4 +1,5 @@
import {
+ BrainIcon,
ChartIncreaseIcon,
CreditCardIcon,
Key01Icon,
@@ -8,11 +9,13 @@ import {
UserIcon,
} from "@hugeicons/core-free-icons";
import type { IconSvgElement } from "@hugeicons/react";
+import { Flag } from "@/services/feature-flags/use-get-flag";
export interface SettingsNavItem {
label: string;
href: string;
Icon: IconSvgElement;
+ flag?: Flag;
}
export const settingsNavItems: SettingsNavItem[] = [
@@ -22,6 +25,12 @@ export const settingsNavItems: SettingsNavItem[] = [
href: "/settings/account",
Icon: SlidersHorizontalIcon,
},
+ {
+ label: "Memory",
+ href: "/settings/memory",
+ Icon: BrainIcon,
+ flag: Flag.GRAPHITI_MEMORY,
+ },
{ label: "Billing", href: "/settings/billing", Icon: CreditCardIcon },
{
label: "Integrations",
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/useSettingsSidebar.ts b/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/useSettingsSidebar.ts
index 04ea4129f2..871c239116 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/useSettingsSidebar.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/useSettingsSidebar.ts
@@ -1,15 +1,19 @@
import { usePathname } from "next/navigation";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { settingsNavItems } from "./helpers";
export function useSettingsSidebar() {
const pathname = usePathname();
+ const isMemoryEnabled = useGetFlag(Flag.GRAPHITI_MEMORY);
- const items = settingsNavItems.map((item) => ({
- ...item,
- isActive:
- pathname === item.href ||
- (item.href !== "/settings" && pathname.startsWith(`${item.href}/`)),
- }));
+ const items = settingsNavItems
+ .filter((item) => item.flag !== Flag.GRAPHITI_MEMORY || isMemoryEnabled)
+ .map((item) => ({
+ ...item,
+ isActive:
+ pathname === item.href ||
+ (item.href !== "/settings" && pathname.startsWith(`${item.href}/`)),
+ }));
return { items };
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/memory/__tests__/main.test.tsx
new file mode 100644
index 0000000000..b6a6982a5c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/__tests__/main.test.tsx
@@ -0,0 +1,300 @@
+import { render, screen, waitFor } from "@/tests/integrations/test-utils";
+import userEvent from "@testing-library/user-event";
+import { http } from "msw";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { resetCopilotChatRegistry } from "@/app/(platform)/copilot/copilotChatRegistry";
+import { TEST_BACKEND_BASE_URL } from "@/app/(platform)/copilot/__tests__/sse-helpers";
+import {
+ getListExpertsMockHandler200,
+ getListExpertsResponseMock200,
+} from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import {
+ getGetV2GetSessionMockHandler200,
+ getGetV2GetSessionResponseMock200,
+ getPostV2CreateSessionMockHandler200,
+ getPostV2CreateSessionResponseMock200,
+} from "@/app/api/__generated__/endpoints/chat/chat.msw";
+import {
+ getEraseMyMemoryMockHandler200,
+ getForgetMyMemoryFactMockHandler200,
+ getGetMyExpertMemoryOverviewMockHandler200,
+ getGetMyMemoryOverviewMockHandler200,
+ getListMyExpertMemoryFactsMockHandler200,
+ getListMyMemoryFactsMockHandler200,
+} from "@/app/api/__generated__/endpoints/memory/memory.msw";
+import { server } from "@/mocks/mock-server";
+import {
+ assistantTextChunks,
+ streamSseResponse,
+} from "@/tests/integrations/copilot-sse";
+
+// The CoPilot stream transport talks to the backend host directly (it
+// bypasses the Next proxy), so MSW must match an absolute URL.
+vi.mock("@/services/environment", async (importActual) => {
+ const actual = await importActual<typeof import("@/services/environment")>();
+ return {
+ ...actual,
+ environment: {
+ ...actual.environment,
+ getAGPTServerBaseUrl: () => TEST_BACKEND_BASE_URL,
+ },
+ };
+});
+
+vi.mock("@/app/(platform)/copilot/helpers", async (importActual) => {
+ const actual =
+ await importActual<typeof import("@/app/(platform)/copilot/helpers")>();
+ return {
+ ...actual,
+ getCopilotAuthHeaders: async () => ({ "x-test-auth": "yes" }),
+ };
+});
+
+vi.mock("@/services/feature-flags/use-get-flag", () => ({
+ Flag: {
+ GRAPHITI_MEMORY: "graphiti-memory",
+ HIRE_EXPERTS: "hire-experts",
+ ARTIFACTS: "artifacts",
+ CHAT_MODE_OPTION: "chat-mode-option",
+ ENABLE_PLATFORM_PAYMENT: "enable-platform-payment",
+ },
+ useGetFlag: (flag: string) =>
+ flag === "graphiti-memory" || flag === "hire-experts",
+}));
+
+vi.mock("@/services/feature-flags/with-feature-flag", () => ({
+ withFeatureFlag: (Component: React.ComponentType) => Component,
+}));
+
+import SettingsMemoryPage from "../page";
+
+const SESSION_ID = "memory-chat-session-1";
+
+const FACTS = {
+ expert_id: null,
+ items: [
+ {
+ uuid: "edge-1",
+ fact: "Runs a DTC candle brand called Emberline",
+ name: "runs",
+ source: "User",
+ target: "Emberline",
+ created_at: "2026-08-16T00:00:00Z",
+ },
+ {
+ uuid: "edge-2",
+ fact: "Prefers weekly summary emails on Monday mornings",
+ name: "prefers",
+ source: "User",
+ target: "Monday summaries",
+ created_at: "2026-08-14T00:00:00Z",
+ },
+ ],
+};
+
+function mockHappyPath() {
+ server.use(
+ getListExpertsMockHandler200([]),
+ getListMyMemoryFactsMockHandler200(FACTS),
+ getGetMyMemoryOverviewMockHandler200({
+ expert_id: null,
+ facts: 214,
+ entities: 90,
+ episodes: 41,
+ }),
+ );
+}
+
+beforeEach(() => {
+ resetCopilotChatRegistry();
+});
+
+describe("Settings memory page", () => {
+ it("renders recent memories for the AutoPilot scope", async () => {
+ mockHappyPath();
+ render(<SettingsMemoryPage />);
+
+ expect(
+ await screen.findByText("Runs a DTC candle brand called Emberline"),
+ ).toBeDefined();
+ expect(
+ screen.getByText("Prefers weekly summary emails on Monday mornings"),
+ ).toBeDefined();
+ expect(screen.getByRole("heading", { name: "Memory" })).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: "View my summary" }),
+ ).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: "Forget a topic…" }),
+ ).toBeDefined();
+ });
+
+ it("shows the empty state when nothing is remembered yet", async () => {
+ server.use(
+ getListExpertsMockHandler200([]),
+ getListMyMemoryFactsMockHandler200({ expert_id: null, items: [] }),
+ getGetMyMemoryOverviewMockHandler200({
+ expert_id: null,
+ facts: 0,
+ entities: 0,
+ episodes: 0,
+ }),
+ );
+ render(<SettingsMemoryPage />);
+
+ expect(await screen.findByText(/Nothing remembered yet/)).toBeDefined();
+ });
+
+ it("forgets a single fact", async () => {
+ mockHappyPath();
+ const forgotten: string[] = [];
+ server.use(
+ getForgetMyMemoryFactMockHandler200((info) => {
+ forgotten.push(String(info.params.factUuid));
+ return { uuid: String(info.params.factUuid), forgotten: true };
+ }),
+ );
+ render(<SettingsMemoryPage />);
+
+ await screen.findByText("Runs a DTC candle brand called Emberline");
+ const user = userEvent.setup();
+ await user.click(screen.getAllByRole("button", { name: "Forget" })[0]);
+
+ await waitFor(() => expect(forgotten).toEqual(["edge-1"]));
+ });
+
+ it("gates the scope erase behind typed confirmation", async () => {
+ mockHappyPath();
+ let erased = false;
+ server.use(
+ getEraseMyMemoryMockHandler200(() => {
+ erased = true;
+ return { expert_id: null, deleted_nodes: 214, erased: true };
+ }),
+ );
+ render(<SettingsMemoryPage />);
+
+ await screen.findByText("Runs a DTC candle brand called Emberline");
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: "Erase memory" }));
+
+ const confirm = await screen.findByRole("button", {
+ name: "Erase everything",
+ });
+ expect(confirm.hasAttribute("disabled")).toBe(true);
+ expect(screen.getByText(/214 memories/)).toBeDefined();
+
+ await user.type(screen.getByPlaceholderText("AutoPilot"), "AutoPilot");
+ await waitFor(() => expect(confirm.hasAttribute("disabled")).toBe(false));
+
+ await user.click(confirm);
+ await waitFor(() => expect(erased).toBe(true));
+ });
+
+ it("switches scope to an expert through the scope selector", async () => {
+ const maria = {
+ ...getListExpertsResponseMock200()[0],
+ id: "expert-maria",
+ name: "Maria",
+ role: "Growth Marketer",
+ avatar_url: null,
+ is_archived: false,
+ };
+ const expertFactRequests: string[] = [];
+ server.use(
+ getListExpertsMockHandler200([maria]),
+ getListMyMemoryFactsMockHandler200(FACTS),
+ getGetMyMemoryOverviewMockHandler200({
+ expert_id: null,
+ facts: 214,
+ entities: 90,
+ episodes: 41,
+ }),
+ getListMyExpertMemoryFactsMockHandler200((info) => {
+ expertFactRequests.push(String(info.params.expertId));
+ return {
+ expert_id: "expert-maria",
+ items: [
+ {
+ uuid: "edge-m1",
+ fact: "Q4 campaign brief is due Friday",
+ name: "due",
+ source: "Campaign",
+ target: "Friday",
+ created_at: "2026-08-17T00:00:00Z",
+ },
+ ],
+ };
+ }),
+ getGetMyExpertMemoryOverviewMockHandler200({
+ expert_id: "expert-maria",
+ facts: 12,
+ entities: 8,
+ episodes: 3,
+ }),
+ );
+ render(<SettingsMemoryPage />);
+
+ await screen.findByText("Runs a DTC candle brand called Emberline");
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: "Memory scope" }));
+ await user.click(
+ await screen.findByRole("menuitem", { name: /Growth Marketer/ }),
+ );
+
+ expect(
+ await screen.findByText("Q4 campaign brief is due Friday"),
+ ).toBeDefined();
+ expect(expertFactRequests).toEqual(["expert-maria"]);
+ expect(
+ screen.getByRole("button", { name: "View Maria's summary" }),
+ ).toBeDefined();
+ expect(screen.getByRole("button", { name: "Erase memory" })).toBeDefined();
+ expect(screen.getByText(/Erase Maria's memory/)).toBeDefined();
+ });
+
+ it("opens the summary chat in-pane and auto-sends the seeded prompt", async () => {
+ mockHappyPath();
+ const createBodies: unknown[] = [];
+ const streamBodies: string[] = [];
+ server.use(
+ getPostV2CreateSessionMockHandler200(async (info) => {
+ createBodies.push(await info.request.clone().json());
+ return getPostV2CreateSessionResponseMock200({ id: SESSION_ID });
+ }),
+ getGetV2GetSessionMockHandler200(
+ getGetV2GetSessionResponseMock200({
+ id: SESSION_ID,
+ messages: [],
+ active_stream: null,
+ }),
+ ),
+ http.post(
+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${SESSION_ID}/stream`,
+ async ({ request }) => {
+ streamBodies.push(await request.clone().text());
+ return streamSseResponse(
+ assistantTextChunks("Here's what I know about you."),
+ { abortSignal: request.signal },
+ );
+ },
+ ),
+ );
+ render(<SettingsMemoryPage />);
+
+ await screen.findByText("Runs a DTC candle brand called Emberline");
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: "View my summary" }));
+
+ expect(await screen.findByText("AutoPilot's memory")).toBeDefined();
+ await waitFor(() => expect(createBodies.length).toBe(1));
+ await waitFor(() => expect(streamBodies.length).toBe(1));
+ expect(streamBodies[0]).toContain(
+ "Give me a summary of everything you know about me",
+ );
+ expect(
+ await screen.findByText("Here's what I know about you."),
+ ).toBeDefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/EraseMemoryCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/EraseMemoryCard.tsx
new file mode 100644
index 0000000000..64921e7a07
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/EraseMemoryCard.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Input } from "@/components/atoms/Input/Input";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { useState } from "react";
+
+interface Props {
+ scopeName: string;
+ memoryCount: number | null;
+ isErasing: boolean;
+ onErase: () => Promise<boolean>;
+}
+
+export function EraseMemoryCard({
+ scopeName,
+ memoryCount,
+ isErasing,
+ onErase,
+}: Props) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [confirmText, setConfirmText] = useState("");
+ const isConfirmed = confirmText.trim() === scopeName;
+
+ async function handleErase() {
+ if (!isConfirmed) return;
+ const erased = await onErase();
+ if (erased) setIsOpen(false);
+ }
+
+ return (
+ <div className="flex flex-col gap-3 rounded-[18px] border border-red-200 bg-white px-4 py-4 shadow-[0_1px_2px_rgba(15,15,20,0.04)] sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex min-w-0 flex-col">
+ <Text variant="body-medium" as="span" className="text-red-700">
+ Erase {scopeName}&apos;s memory
+ </Text>
+ <Text variant="small" as="span" className="text-zinc-500">
+ Permanently delete everything this memory holds. This can&apos;t be
+ undone.
+ </Text>
+ </div>
+ <Dialog
+ title={`Erase all of ${scopeName}'s memory`}
+ styling={{ maxWidth: "440px" }}
+ controlled={{
+ isOpen,
+ set: (open) => {
+ setIsOpen(open);
+ if (open) setConfirmText("");
+ },
+ }}
+ >
+ <Dialog.Trigger>
+ <Button variant="destructive" size="small">
+ Erase memory
+ </Button>
+ </Dialog.Trigger>
+ <Dialog.Content>
+ <div className="flex flex-col gap-4">
+ <Text variant="small" as="p" className="text-zinc-600">
+ {memoryCount !== null
+ ? `Every memory in this scope will be permanently deleted — ${memoryCount} ${memoryCount === 1 ? "memory" : "memories"}, raw conversations included. Other scopes are not affected.`
+ : "Every memory in this scope will be permanently deleted, raw conversations included. Other scopes are not affected."}{" "}
+ Type <strong>{scopeName}</strong> to confirm.
+ </Text>
+ <Input
+ id="erase-memory-confirm"
+ label={`Type ${scopeName} to confirm`}
+ hideLabel
+ placeholder={scopeName}
+ value={confirmText}
+ onChange={(e) => setConfirmText(e.target.value)}
+ />
+ <div className="flex justify-end gap-2">
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => setIsOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ size="small"
+ disabled={!isConfirmed}
+ loading={isErasing}
+ onClick={handleErase}
+ >
+ Erase everything
+ </Button>
+ </div>
+ </div>
+ </Dialog.Content>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/MemoryChatPanel/MemoryChatPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/MemoryChatPanel/MemoryChatPanel.tsx
new file mode 100644
index 0000000000..18c7d08577
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/MemoryChatPanel/MemoryChatPanel.tsx
@@ -0,0 +1,120 @@
+"use client";
+
+import { ChatInput } from "@/app/(platform)/copilot/components/ChatInput/ChatInput";
+import { ChatMessagesContainer } from "@/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer";
+import { CopilotChatActionsProvider } from "@/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider";
+import { Button } from "@/components/atoms/Button/Button";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { BrainIcon, Cancel01Icon } from "@hugeicons/core-free-icons";
+
+interface Props {
+ scopeName: string;
+ isOpen: boolean;
+ isStarting: boolean;
+ startError: boolean;
+ sessionId: string | null;
+ messages: React.ComponentProps<typeof ChatMessagesContainer>["messages"];
+ status: React.ComponentProps<typeof ChatMessagesContainer>["status"];
+ error: React.ComponentProps<typeof ChatMessagesContainer>["error"];
+ queuedMessages: React.ComponentProps<
+ typeof ChatMessagesContainer
+ >["queuedMessages"];
+ onSend: (message: string) => Promise<void>;
+ onStop: () => void;
+ onRetry: () => void;
+ onClose: () => void;
+}
+
+export function MemoryChatPanel({
+ scopeName,
+ isOpen,
+ isStarting,
+ startError,
+ sessionId,
+ messages,
+ status,
+ error,
+ queuedMessages,
+ onSend,
+ onStop,
+ onRetry,
+ onClose,
+}: Props) {
+ if (!isOpen) return null;
+
+ const isStreaming = status === "streaming" || status === "submitted";
+
+ return (
+ <div className="pointer-events-none fixed bottom-4 right-4 z-50 flex flex-col items-end">
+ <CopilotChatActionsProvider onSend={onSend}>
+ <div
+ role="complementary"
+ aria-label="Memory chat panel"
+ className="pointer-events-auto flex h-[70vh] max-h-[calc(100vh-6rem)] w-[26rem] max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-xl border border-zinc-200 bg-white shadow-2xl sm:h-[75vh]"
+ >
+ <div className="flex items-center justify-between border-b border-zinc-100 px-4 py-3">
+ <div className="flex items-center gap-2">
+ <Icon icon={BrainIcon} size={18} className="text-violet-600" />
+ <span className="text-sm font-semibold text-zinc-800">
+ {scopeName}&apos;s memory
+ </span>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={onClose}
+ aria-label="Close memory chat"
+ >
+ <Icon icon={Cancel01Icon} size={16} />
+ </Button>
+ </div>
+
+ <div className="flex h-0 min-h-0 flex-1 flex-col">
+ {startError ? (
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-4 py-6 text-center text-sm text-zinc-600">
+ <p className="font-medium text-zinc-800">
+ Could not start the memory chat
+ </p>
+ <p className="text-zinc-500">
+ Something went wrong. Retry to try again.
+ </p>
+ <Button variant="secondary" size="small" onClick={onRetry}>
+ Retry
+ </Button>
+ </div>
+ ) : isStarting || !sessionId ? (
+ <div className="flex flex-1 items-center justify-center px-4 py-6 text-sm text-zinc-500">
+ Starting memory chat…
+ </div>
+ ) : (
+ <>
+ <div className="flex min-h-0 flex-1 flex-col">
+ <ChatMessagesContainer
+ messages={messages}
+ status={status}
+ error={error}
+ isLoading={false}
+ sessionID={sessionId}
+ queuedMessages={queuedMessages}
+ />
+ </div>
+ <div className="relative shrink-0 border-t border-zinc-100 bg-white px-3 pb-2 pt-2">
+ <ChatInput
+ inputId="memory-chat-input"
+ onSend={onSend}
+ disabled={false}
+ isStreaming={isStreaming}
+ onStop={onStop}
+ onEnqueue={onSend}
+ placeholder="Ask or update…"
+ hasSession={true}
+ />
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ </CopilotChatActionsProvider>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/MemoryChatPanel/useMemoryChatPanel.ts b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/MemoryChatPanel/useMemoryChatPanel.ts
new file mode 100644
index 0000000000..0e8a5d8c52
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/MemoryChatPanel/useMemoryChatPanel.ts
@@ -0,0 +1,185 @@
+import { convertChatSessionMessagesToUiMessages } from "@/app/(platform)/copilot/helpers/convertChatSessionToUiMessages";
+import { queueFollowUpMessage } from "@/app/(platform)/copilot/helpers/queueFollowUpMessage";
+import { useCopilotPendingChips } from "@/app/(platform)/copilot/useCopilotPendingChips";
+import { useCopilotStream } from "@/app/(platform)/copilot/useCopilotStream";
+import {
+ useGetV2GetSession,
+ usePostV2CreateSession,
+} from "@/app/api/__generated__/endpoints/chat/chat";
+import { toast } from "@/components/molecules/Toast/use-toast";
+import * as Sentry from "@sentry/nextjs";
+import type { UIDataTypes, UIMessage, UITools } from "ai";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { MEMORY_CHAT_PROMPTS, type MemoryChatSeed } from "../../helpers";
+
+type UiMessages = UIMessage<unknown, UIDataTypes, UITools>[];
+
+interface Args {
+ scopeExpertID: string | null;
+}
+
+/**
+ * In-pane memory chat, modeled on the builder's chat panel: reuses the
+ * copilot chat primitives against a session created here. Every open
+ * starts a fresh session for the current scope and auto-sends the seed
+ * prompt ("summary" or "forget") as its first message.
+ */
+export function useMemoryChatPanel({ scopeExpertID }: Args) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [sessionId, setSessionId] = useState<string | null>(null);
+ const [startError, setStartError] = useState(false);
+ const pendingPromptRef = useRef<string | null>(null);
+ // Session-create lock, keyed by scope generation: a stale in-flight create
+ // for a previous scope must not block the new scope's first open.
+ const openingGenRef = useRef<number | null>(null);
+ const lastSeedRef = useRef<MemoryChatSeed | null>(null);
+
+ const { mutateAsync: createSession } = usePostV2CreateSession();
+
+ const sessionQuery = useGetV2GetSession(sessionId ?? "", undefined, {
+ query: {
+ enabled: !!sessionId,
+ staleTime: Infinity,
+ refetchOnWindowFocus: false,
+ refetchOnMount: true,
+ },
+ });
+ const hasActiveStream =
+ sessionQuery.data?.status === 200
+ ? !!sessionQuery.data.data.active_stream
+ : false;
+
+ const hydratedMessages = useMemo<UiMessages | undefined>(() => {
+ if (sessionQuery.data?.status !== 200 || !sessionId) return undefined;
+ return convertChatSessionMessagesToUiMessages(
+ sessionId,
+ sessionQuery.data.data.messages ?? [],
+ { isComplete: !hasActiveStream },
+ ).messages as UiMessages;
+ }, [sessionQuery.data, sessionId, hasActiveStream]);
+
+ const { messages, setMessages, sendMessage, stop, status, error } =
+ useCopilotStream({
+ sessionId,
+ hydratedMessages,
+ hasActiveStream,
+ refetchSession: sessionQuery.refetch,
+ copilotMode: undefined,
+ copilotModel: undefined,
+ });
+
+ const { queuedMessages, queueMessage } = useCopilotPendingChips({
+ sessionId,
+ status,
+ messages,
+ setMessages,
+ });
+
+ // The seed fires from an effect so it runs only after the stream hook has
+ // re-rendered bound to the just-created session.
+ useEffect(() => {
+ if (!sessionId || !pendingPromptRef.current) return;
+ const prompt = pendingPromptRef.current;
+ pendingPromptRef.current = null;
+ sendMessage({ text: prompt });
+ }, [sessionId, sendMessage]);
+
+ // Switching scope invalidates the open conversation — reset everything and
+ // bump the generation so an in-flight session create for the old scope is
+ // discarded instead of binding its session under the new scope's name.
+ const scopeRef = useRef(scopeExpertID);
+ const scopeGenRef = useRef(0);
+ useEffect(() => {
+ if (scopeRef.current === scopeExpertID) return;
+ scopeRef.current = scopeExpertID;
+ scopeGenRef.current += 1;
+ setIsOpen(false);
+ setSessionId(null);
+ setMessages([]);
+ pendingPromptRef.current = null;
+ }, [scopeExpertID, setMessages]);
+
+ async function openWithSeed(seed: MemoryChatSeed) {
+ // Latest requested seed wins: a second click during the create-session
+ // window updates what gets auto-sent (and what retry re-sends).
+ lastSeedRef.current = seed;
+ setIsOpen(true);
+ setStartError(false);
+ if (openingGenRef.current === scopeGenRef.current) return;
+ const generation = scopeGenRef.current;
+ openingGenRef.current = generation;
+ setSessionId(null);
+ setMessages([]);
+ try {
+ const response = (await createSession(
+ scopeExpertID ? { data: { expert_id: scopeExpertID } } : { data: null },
+ )) as unknown as { status: number; data?: { id?: string } };
+ if (response.status !== 200 || !response.data?.id) {
+ throw new Error("Failed to create memory chat session");
+ }
+ if (generation !== scopeGenRef.current) return;
+ pendingPromptRef.current = MEMORY_CHAT_PROMPTS[lastSeedRef.current];
+ setSessionId(response.data.id);
+ } catch (err) {
+ Sentry.captureException(err);
+ if (generation === scopeGenRef.current) setStartError(true);
+ } finally {
+ // Only release the lock if this call still owns it — a superseded
+ // create must not unlock a newer scope's in-flight create.
+ if (openingGenRef.current === generation) openingGenRef.current = null;
+ }
+ }
+
+ function retryStart() {
+ if (lastSeedRef.current) void openWithSeed(lastSeedRef.current);
+ }
+
+ function close() {
+ setIsOpen(false);
+ }
+
+ async function onSend(message: string) {
+ const trimmed = message.trim();
+ if (!trimmed || !sessionId) return;
+ const isInFlight = status === "streaming" || status === "submitted";
+ if (isInFlight) {
+ try {
+ await queueFollowUpMessage(sessionId, trimmed);
+ queueMessage(trimmed);
+ } catch (err) {
+ // The turn finished while we were queueing — send normally instead.
+ if (
+ err instanceof Error &&
+ err.name === "QueueFollowUpNotActiveError"
+ ) {
+ sendMessage({ text: trimmed });
+ return;
+ }
+ Sentry.captureException(err);
+ toast({
+ variant: "destructive",
+ title: "Could not queue message",
+ description: "Please wait for the current response to finish.",
+ });
+ }
+ return;
+ }
+ sendMessage({ text: trimmed });
+ }
+
+ return {
+ isOpen,
+ openWithSeed,
+ close,
+ retryStart,
+ startError,
+ isStarting: isOpen && !sessionId && !startError,
+ sessionId,
+ messages,
+ status,
+ error,
+ stop,
+ onSend,
+ queuedMessages,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/RecentMemoriesCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/RecentMemoriesCard.tsx
new file mode 100644
index 0000000000..0858ab8ca1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/RecentMemoriesCard.tsx
@@ -0,0 +1,87 @@
+"use client";
+
+import type { MemoryFact } from "@/app/api/__generated__/models/memoryFact";
+import { Button } from "@/components/atoms/Button/Button";
+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
+import { Text } from "@/components/atoms/Text/Text";
+import { formatWhen } from "../helpers";
+
+interface Props {
+ facts: MemoryFact[];
+ isLoading: boolean;
+ forgettingUuid: string | null;
+ onForget: (uuid: string) => void;
+ onForgetTopic: () => void;
+}
+
+export function RecentMemoriesCard({
+ facts,
+ isLoading,
+ forgettingUuid,
+ onForget,
+ onForgetTopic,
+}: Props) {
+ return (
+ <div className="flex flex-col rounded-[18px] border border-zinc-200 bg-white px-4 py-4 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">
+ <Text variant="body-medium" as="span" className="text-textBlack">
+ Recent memories
+ </Text>
+ <Text variant="small" as="span" className="text-zinc-500">
+ The latest things this memory has learned. Forget any of them.
+ </Text>
+
+ <div className="mt-2 flex flex-col divide-y divide-zinc-100">
+ {isLoading ? (
+ <div className="flex flex-col gap-2 py-3">
+ <Skeleton className="h-5 w-3/4" />
+ <Skeleton className="h-5 w-2/3" />
+ <Skeleton className="h-5 w-4/5" />
+ </div>
+ ) : facts.length === 0 ? (
+ <Text variant="small" as="p" className="py-3 text-zinc-500">
+ Nothing remembered yet. Memories show up here as you chat.
+ </Text>
+ ) : (
+ facts.map((fact) => (
+ <div
+ key={fact.uuid}
+ className="flex items-center justify-between gap-3 py-2.5"
+ >
+ <Text
+ variant="small"
+ as="span"
+ unmask={false}
+ className="min-w-0 flex-1 text-textBlack"
+ >
+ {fact.fact || `${fact.source} → ${fact.target}`}
+ </Text>
+ <Text
+ variant="small"
+ as="span"
+ unmask={false}
+ className="hidden shrink-0 text-zinc-400 sm:inline"
+ >
+ {formatWhen(fact.created_at)}
+ </Text>
+ <Button
+ variant="ghost"
+ size="small"
+ className="h-7 !min-w-0 shrink-0 px-2 text-zinc-600"
+ loading={forgettingUuid === fact.uuid}
+ onClick={() => onForget(fact.uuid)}
+ >
+ Forget
+ </Button>
+ </div>
+ ))
+ )}
+ </div>
+
+ <div className="mt-3">
+ <Button variant="secondary" size="small" onClick={onForgetTopic}>
+ Forget a topic…
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/ScopeCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/ScopeCard.tsx
new file mode 100644
index 0000000000..19cd2b7b10
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/ScopeCard.tsx
@@ -0,0 +1,33 @@
+"use client";
+
+import type { Expert } from "@/app/api/__generated__/models/expert";
+import { Text } from "@/components/atoms/Text/Text";
+import { ScopeSelect } from "./ScopeSelect";
+
+interface Props {
+ scopeExpertID: string | null;
+ experts: Expert[];
+ onSelect: (expertID: string | null) => void;
+}
+
+export function ScopeCard({ scopeExpertID, experts, onSelect }: Props) {
+ return (
+ <div className="flex flex-col gap-3 rounded-[18px] border border-zinc-200 bg-white px-4 py-4 shadow-[0_1px_2px_rgba(15,15,20,0.04)] sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex min-w-0 flex-col">
+ <Text variant="body-medium" as="span" className="text-textBlack">
+ Memory scope
+ </Text>
+ <Text variant="small" as="span" className="text-zinc-500">
+ Choose whose memory you&apos;re looking at. Experts keep their own.
+ </Text>
+ </div>
+ <div className="w-full sm:w-[280px]">
+ <ScopeSelect
+ scopeExpertID={scopeExpertID}
+ experts={experts}
+ onSelect={onSelect}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/ScopeSelect.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/ScopeSelect.tsx
new file mode 100644
index 0000000000..1affd52da6
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/ScopeSelect.tsx
@@ -0,0 +1,136 @@
+"use client";
+
+import type { Expert } from "@/app/api/__generated__/models/expert";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/molecules/DropdownMenu/DropdownMenu";
+import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";
+import { cn } from "@/lib/utils";
+import { ArrowDown01Icon, Tick02Icon } from "@hugeicons/core-free-icons";
+
+interface Props {
+ scopeExpertID: string | null;
+ experts: Expert[];
+ onSelect: (expertID: string | null) => void;
+}
+
+function AutoPilotAvatar({ size }: { size: number }) {
+ return (
+ <div
+ style={{ width: size, height: size }}
+ className="flex shrink-0 items-center justify-center rounded-full bg-violet-600 font-semibold text-white"
+ >
+ <span style={{ fontSize: size * 0.45 }}>A</span>
+ </div>
+ );
+}
+
+function ScopeCheck({ selected }: { selected: boolean }) {
+ if (!selected) return null;
+ return (
+ <Icon
+ icon={Tick02Icon}
+ size={16}
+ className="ml-auto shrink-0 text-violet-600"
+ />
+ );
+}
+
+export function ScopeSelect({ scopeExpertID, experts, onSelect }: Props) {
+ const selectedExpert = scopeExpertID
+ ? experts.find((expert) => expert.id === scopeExpertID)
+ : undefined;
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label="Memory scope"
+ className={cn(
+ "flex w-full items-center gap-2.5 rounded-[10px] border border-zinc-200 bg-white px-3 py-2 text-sm font-medium text-textBlack",
+ "transition-colors hover:border-zinc-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400",
+ "data-[state=open]:border-violet-500",
+ )}
+ >
+ {selectedExpert ? (
+ <ExpertAvatar
+ name={selectedExpert.name}
+ avatarUrl={selectedExpert.avatar_url}
+ size={24}
+ />
+ ) : (
+ <AutoPilotAvatar size={24} />
+ )}
+ <span className="min-w-0 truncate">
+ {selectedExpert?.name ?? "AutoPilot"}
+ </span>
+ <Icon
+ icon={ArrowDown01Icon}
+ size={16}
+ className="ml-auto shrink-0 text-zinc-500"
+ />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className="max-h-96 w-[300px] overflow-y-auto rounded-[12px] p-1.5"
+ >
+ <DropdownMenuItem
+ className="flex items-start gap-2.5 rounded-[8px] px-2.5 py-2"
+ onSelect={() => onSelect(null)}
+ >
+ <AutoPilotAvatar size={28} />
+ <span className="flex min-w-0 flex-col leading-snug">
+ <span className="text-sm font-medium text-textBlack">
+ AutoPilot
+ </span>
+ <span className="text-xs text-zinc-500">
+ Your account memory — everything you do together
+ </span>
+ </span>
+ <ScopeCheck selected={scopeExpertID === null} />
+ </DropdownMenuItem>
+
+ {experts.length > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel className="px-2.5 pb-0.5 pt-1.5 text-[10px] font-semibold uppercase tracking-[0.12em] text-zinc-400">
+ Your experts
+ </DropdownMenuLabel>
+ {experts.map((expert) => (
+ <DropdownMenuItem
+ key={expert.id}
+ className="flex items-start gap-2.5 rounded-[8px] px-2.5 py-2"
+ onSelect={() => onSelect(expert.id)}
+ >
+ <ExpertAvatar
+ name={expert.name}
+ avatarUrl={expert.avatar_url}
+ size={28}
+ />
+ <span className="flex min-w-0 flex-col leading-snug">
+ <span className="truncate text-sm font-medium text-textBlack">
+ {expert.name}
+ </span>
+ {expert.role && (
+ <span className="truncate text-xs text-zinc-500">
+ {expert.role}
+ </span>
+ )}
+ </span>
+ <ScopeCheck selected={scopeExpertID === expert.id} />
+ </DropdownMenuItem>
+ ))}
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/SummaryCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/SummaryCard.tsx
new file mode 100644
index 0000000000..3eac6504f2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/components/SummaryCard.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+
+interface Props {
+ scopeExpertID: string | null;
+ scopeName: string;
+ onViewSummary: () => void;
+}
+
+export function SummaryCard({
+ scopeExpertID,
+ scopeName,
+ onViewSummary,
+}: Props) {
+ const isAutoPilot = scopeExpertID === null;
+ return (
+ <div className="flex flex-col gap-3 rounded-[18px] border border-zinc-200 bg-white px-4 py-4 shadow-[0_1px_2px_rgba(15,15,20,0.04)] sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex min-w-0 flex-col">
+ <Text variant="body-medium" as="span" className="text-textBlack">
+ Memory summary
+ </Text>
+ <Text variant="small" as="span" className="text-zinc-500">
+ {isAutoPilot
+ ? "Ask AutoPilot what it knows about you. Opens a chat — you can correct or forget anything from there."
+ : `Ask ${scopeName} what they know about you and their work. Opens a chat.`}
+ </Text>
+ </div>
+ <Button variant="primary" size="small" onClick={onViewSummary}>
+ {isAutoPilot ? "View my summary" : `View ${scopeName}'s summary`}
+ </Button>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/memory/helpers.ts
new file mode 100644
index 0000000000..5558b2c77e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/helpers.ts
@@ -0,0 +1,36 @@
+import type { Expert } from "@/app/api/__generated__/models/expert";
+import { formatDistanceToNow } from "date-fns";
+
+export const RECENT_FACTS_LIMIT = 6;
+
+export const AUTOPILOT_SCOPE = "autopilot";
+
+export const MEMORY_CHAT_PROMPTS = {
+ summary: "Give me a summary of everything you know about me",
+ forget:
+ "I'd like you to forget something from your memory. Ask me what to " +
+ "forget, search your memory for matching facts, show me what you find, " +
+ "and only delete after I confirm.",
+} as const;
+
+export type MemoryChatSeed = keyof typeof MEMORY_CHAT_PROMPTS;
+
+export function getActiveExperts(experts: Expert[] | undefined) {
+ return (experts ?? []).filter((expert) => !expert.is_archived);
+}
+
+export function getScopeName(
+ scopeExpertID: string | null,
+ experts: Expert[] | undefined,
+) {
+ if (!scopeExpertID) return "AutoPilot";
+ const expert = experts?.find((e) => e.id === scopeExpertID);
+ return expert?.name ?? "this expert";
+}
+
+export function formatWhen(createdAt: string | null | undefined) {
+ if (!createdAt) return "";
+ const parsed = new Date(createdAt);
+ if (Number.isNaN(parsed.getTime())) return "";
+ return formatDistanceToNow(parsed, { addSuffix: true });
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/page.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/memory/page.tsx
new file mode 100644
index 0000000000..0c0edc0c48
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/page.tsx
@@ -0,0 +1,105 @@
+"use client";
+
+import { Text } from "@/components/atoms/Text/Text";
+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
+import { withFeatureFlag } from "@/services/feature-flags/with-feature-flag";
+import { useEffect } from "react";
+
+import { EraseMemoryCard } from "./components/EraseMemoryCard";
+import { MemoryChatPanel } from "./components/MemoryChatPanel/MemoryChatPanel";
+import { useMemoryChatPanel } from "./components/MemoryChatPanel/useMemoryChatPanel";
+import { RecentMemoriesCard } from "./components/RecentMemoriesCard";
+import { ScopeCard } from "./components/ScopeCard";
+import { SummaryCard } from "./components/SummaryCard";
+import { useMemoryPage } from "./useMemoryPage";
+
+function SettingsMemoryPage() {
+ useEffect(() => {
+ document.title = "Memory – AutoGPT Platform";
+ }, []);
+
+ const {
+ scopeExpertID,
+ selectScope,
+ experts,
+ scopeName,
+ facts,
+ isLoadingFacts,
+ isFactsError,
+ factsError,
+ refetchFacts,
+ memoryCount,
+ forgetFact,
+ forgettingUuid,
+ eraseScope,
+ isErasing,
+ } = useMemoryPage();
+
+ const chatPanel = useMemoryChatPanel({ scopeExpertID });
+
+ return (
+ <div className="flex flex-col gap-4">
+ <header className="flex min-w-0 flex-col pb-2 pl-4">
+ <Text variant="h4" as="h1" className="leading-[28px] text-textBlack">
+ Memory
+ </Text>
+ <Text variant="body" className="mt-4 max-w-[600px] text-zinc-700">
+ What AutoGPT remembers about you — and who remembers it.
+ </Text>
+ </header>
+
+ <ScopeCard
+ scopeExpertID={scopeExpertID}
+ experts={experts}
+ onSelect={selectScope}
+ />
+
+ <SummaryCard
+ scopeExpertID={scopeExpertID}
+ scopeName={scopeName}
+ onViewSummary={() => void chatPanel.openWithSeed("summary")}
+ />
+
+ {isFactsError ? (
+ <ErrorCard
+ responseError={factsError || undefined}
+ context="memory"
+ onRetry={refetchFacts}
+ />
+ ) : (
+ <RecentMemoriesCard
+ facts={facts}
+ isLoading={isLoadingFacts}
+ forgettingUuid={forgettingUuid}
+ onForget={forgetFact}
+ onForgetTopic={() => void chatPanel.openWithSeed("forget")}
+ />
+ )}
+
+ <EraseMemoryCard
+ scopeName={scopeName}
+ memoryCount={memoryCount}
+ isErasing={isErasing}
+ onErase={eraseScope}
+ />
+
+ <MemoryChatPanel
+ scopeName={scopeName}
+ isOpen={chatPanel.isOpen}
+ isStarting={chatPanel.isStarting}
+ startError={chatPanel.startError}
+ sessionId={chatPanel.sessionId}
+ messages={chatPanel.messages}
+ status={chatPanel.status}
+ error={chatPanel.error}
+ queuedMessages={chatPanel.queuedMessages}
+ onSend={chatPanel.onSend}
+ onStop={chatPanel.stop}
+ onRetry={chatPanel.retryStart}
+ onClose={chatPanel.close}
+ />
+ </div>
+ );
+}
+
+export default withFeatureFlag(SettingsMemoryPage, "graphiti-memory");
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/memory/useMemoryPage.ts b/autogpt_platform/frontend/src/app/(platform)/settings/memory/useMemoryPage.ts
new file mode 100644
index 0000000000..e8afbb87f2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/memory/useMemoryPage.ts
@@ -0,0 +1,180 @@
+import {
+ getGetMyExpertMemoryOverviewQueryKey,
+ getGetMyMemoryOverviewQueryKey,
+ getListMyExpertMemoryFactsQueryKey,
+ getListMyMemoryFactsQueryKey,
+ useEraseMyExpertMemory,
+ useEraseMyMemory,
+ useForgetMyExpertMemoryFact,
+ useForgetMyMemoryFact,
+ useGetMyExpertMemoryOverview,
+ useGetMyMemoryOverview,
+ useListMyExpertMemoryFacts,
+ useListMyMemoryFacts,
+} from "@/app/api/__generated__/endpoints/memory/memory";
+import { useListExperts } from "@/app/api/__generated__/endpoints/experts/experts";
+import { toast } from "@/components/molecules/Toast/use-toast";
+import { useQueryClient } from "@tanstack/react-query";
+import { useEffect, useState } from "react";
+import { getActiveExperts, getScopeName, RECENT_FACTS_LIMIT } from "./helpers";
+
+export function useMemoryPage() {
+ const [scopeExpertID, setScopeExpertID] = useState<string | null>(null);
+ const queryClient = useQueryClient();
+
+ // Deliberately not gated on HIRE_EXPERTS: expert memory scopes must stay
+ // manageable here even if the hiring UI is dark.
+ const expertsQuery = useListExperts();
+ const expertsSettled = expertsQuery.data?.status === 200;
+ const experts = getActiveExperts(
+ expertsQuery.data?.status === 200 ? expertsQuery.data.data : undefined,
+ );
+
+ // A selected expert can disappear (fired in another tab, roster changed) —
+ // fall back to AutoPilot instead of driving queries with a dead scope id.
+ useEffect(() => {
+ if (!scopeExpertID || !expertsSettled) return;
+ if (!experts.some((expert) => expert.id === scopeExpertID)) {
+ setScopeExpertID(null);
+ }
+ }, [scopeExpertID, expertsSettled, experts]);
+
+ const accountFacts = useListMyMemoryFacts(
+ { limit: RECENT_FACTS_LIMIT },
+ { query: { enabled: scopeExpertID === null } },
+ );
+ const expertFacts = useListMyExpertMemoryFacts(
+ scopeExpertID ?? "",
+ { limit: RECENT_FACTS_LIMIT },
+ { query: { enabled: scopeExpertID !== null } },
+ );
+ const factsQuery = scopeExpertID === null ? accountFacts : expertFacts;
+ const facts =
+ factsQuery.data?.status === 200 ? factsQuery.data.data.items : [];
+
+ const accountOverview = useGetMyMemoryOverview({
+ query: { enabled: scopeExpertID === null },
+ });
+ const expertOverview = useGetMyExpertMemoryOverview(scopeExpertID ?? "", {
+ query: { enabled: scopeExpertID !== null },
+ });
+ const overviewQuery =
+ scopeExpertID === null ? accountOverview : expertOverview;
+ const overview =
+ overviewQuery.data?.status === 200 ? overviewQuery.data.data : undefined;
+
+ function invalidateScopeQueries() {
+ if (scopeExpertID === null) {
+ queryClient.invalidateQueries({
+ queryKey: getListMyMemoryFactsQueryKey(),
+ });
+ queryClient.invalidateQueries({
+ queryKey: getGetMyMemoryOverviewQueryKey(),
+ });
+ return;
+ }
+ queryClient.invalidateQueries({
+ queryKey: getListMyExpertMemoryFactsQueryKey(scopeExpertID),
+ });
+ queryClient.invalidateQueries({
+ queryKey: getGetMyExpertMemoryOverviewQueryKey(scopeExpertID),
+ });
+ }
+
+ function onForgotten() {
+ invalidateScopeQueries();
+ toast({ title: "Forgotten" });
+ }
+
+ function onForgetError() {
+ toast({
+ title: "Could not forget that memory",
+ description: "Please try again.",
+ variant: "destructive",
+ });
+ }
+
+ const forgetAccountFact = useForgetMyMemoryFact({
+ mutation: { onSuccess: onForgotten, onError: onForgetError },
+ });
+ const forgetExpertFact = useForgetMyExpertMemoryFact({
+ mutation: { onSuccess: onForgotten, onError: onForgetError },
+ });
+
+ async function forgetFact(uuid: string) {
+ try {
+ if (scopeExpertID === null) {
+ await forgetAccountFact.mutateAsync({ factUuid: uuid });
+ } else {
+ await forgetExpertFact.mutateAsync({
+ expertId: scopeExpertID,
+ factUuid: uuid,
+ });
+ }
+ } catch {
+ // onError already surfaced the toast; keep the rejection out of the
+ // click handler.
+ }
+ }
+
+ const forgettingUuid = forgetAccountFact.isPending
+ ? forgetAccountFact.variables?.factUuid
+ : forgetExpertFact.isPending
+ ? forgetExpertFact.variables?.factUuid
+ : null;
+
+ function onErased() {
+ invalidateScopeQueries();
+ toast({ title: "Memory erased" });
+ }
+
+ function onEraseError() {
+ toast({
+ title: "Could not erase memory",
+ description: "Please try again.",
+ variant: "destructive",
+ });
+ }
+
+ const eraseAccount = useEraseMyMemory({
+ mutation: { onSuccess: onErased, onError: onEraseError },
+ });
+ const eraseExpert = useEraseMyExpertMemory({
+ mutation: { onSuccess: onErased, onError: onEraseError },
+ });
+
+ async function eraseScope() {
+ try {
+ if (scopeExpertID === null) {
+ await eraseAccount.mutateAsync();
+ } else {
+ await eraseExpert.mutateAsync({ expertId: scopeExpertID });
+ }
+ return true;
+ } catch {
+ // onError already surfaced the toast; the caller keeps its dialog open.
+ return false;
+ }
+ }
+
+ function selectScope(value: string | null) {
+ setScopeExpertID(value);
+ }
+
+ return {
+ scopeExpertID,
+ selectScope,
+ experts,
+ scopeName: getScopeName(scopeExpertID, experts),
+ facts,
+ isLoadingFacts: factsQuery.isLoading,
+ isFactsError: factsQuery.isError,
+ factsError: factsQuery.error,
+ refetchFacts: factsQuery.refetch,
+ memoryCount: overview?.facts ?? null,
+ forgetFact,
+ forgettingUuid: forgettingUuid ?? null,
+ eraseScope,
+ isErasing: eraseAccount.isPending || eraseExpert.isPending,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 88abe7bf10..e56164c57a 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -9391,6 +9391,348 @@
"security": [{ "HTTPBearerJWT": [] }]
}
},
+ "/api/memory": {
+ "delete": {
+ "tags": ["v2", "memory", "memory", "private"],
+ "summary": "Erase My Memory",
+ "description": "Permanently erase the caller's entire account memory.",
+ "operationId": "erase_my_memory",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/EraseMemoryResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
+ "/api/memory/experts/{expert_id}": {
+ "delete": {
+ "tags": ["v2", "memory", "memory", "private"],
+ "summary": "Erase My Expert Memory",
+ "description": "Permanently erase one expert's entire isolated memory.",
+ "operationId": "erase_my_expert_memory",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Expert id owned by the caller",
+ "title": "Expert Id"
+ },
+ "description": "Expert id owned by the caller"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/EraseMemoryResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/memory/experts/{expert_id}/facts": {
+ "get": {
+ "tags": ["v2", "memory", "memory", "private"],
+ "summary": "List My Expert Memory Facts",
+ "description": "Live facts in one expert's isolated memory, newest first.",
+ "operationId": "list_my_expert_memory_facts",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Expert id owned by the caller",
+ "title": "Expert Id"
+ },
+ "description": "Expert id owned by the caller"
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 500,
+ "minimum": 1,
+ "default": 50,
+ "title": "Limit"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MemoryFactListResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/memory/experts/{expert_id}/facts/{fact_uuid}": {
+ "delete": {
+ "tags": ["v2", "memory", "memory", "private"],
+ "summary": "Forget My Expert Memory Fact",
+ "description": "Forget one fact from an expert's isolated memory.",
+ "operationId": "forget_my_expert_memory_fact",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Expert id owned by the caller",
+ "title": "Expert Id"
+ },
+ "description": "Expert id owned by the caller"
+ },
+ {
+ "name": "fact_uuid",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Fact edge uuid",
+ "title": "Fact Uuid"
+ },
+ "description": "Fact edge uuid"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/ForgetFactResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/memory/experts/{expert_id}/overview": {
+ "get": {
+ "tags": ["v2", "memory", "memory", "private"],
+ "summary": "Get My Expert Memory Overview",
+ "description": "Counts for one of the caller's experts' isolated memory.",
+ "operationId": "get_my_expert_memory_overview",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Expert id owned by the caller",
+ "title": "Expert Id"
+ },
+ "description": "Expert id owned by the caller"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/MemoryScopeOverview" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/memory/facts": {
+ "get": {
+ "tags": ["v2", "memory", "memory", "private"],
+ "summary": "List My Memory Facts",
+ "description": "Live facts in the caller's account memory, newest first.",
+ "operationId": "list_my_memory_facts",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "limit",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 500,
+ "minimum": 1,
+ "default": 50,
+ "title": "Limit"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MemoryFactListResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/memory/facts/{fact_uuid}": {
+ "delete": {
+ "tags": ["v2", "memory", "memory", "private"],
+ "summary": "Forget My Memory Fact",
+ "description": "Forget one fact from the caller's account memory.",
+ "operationId": "forget_my_memory_fact",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "fact_uuid",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Fact edge uuid",
+ "title": "Fact Uuid"
+ },
+ "description": "Fact edge uuid"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/ForgetFactResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/memory/overview": {
+ "get": {
+ "tags": ["v2", "memory", "memory", "private"],
+ "summary": "Get My Memory Overview",
+ "description": "Counts for the caller's account (AutoPilot) memory.",
+ "operationId": "get_my_memory_overview",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/MemoryScopeOverview" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
"/api/oauth/app/{client_id}": {
"get": {
"tags": ["oauth"],
@@ -17975,6 +18317,20 @@
"required": ["uuid", "name"],
"title": "EntitySummary"
},
+ "EraseMemoryResponse": {
+ "properties": {
+ "expert_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Expert Id"
+ },
+ "deleted_nodes": { "type": "integer", "title": "Deleted Nodes" },
+ "erased": { "type": "boolean", "title": "Erased" }
+ },
+ "type": "object",
+ "required": ["deleted_nodes", "erased"],
+ "title": "EraseMemoryResponse",
+ "description": "Result of a scope wipe. ``deleted_nodes`` counts every node removed —\nentities, episodes (raw text included), and communities."
+ },
"ErrorResponse": {
"properties": {
"type": {
@@ -18966,6 +19322,15 @@
"title": "FolderUpdateRequest",
"description": "Request model for updating a folder."
},
+ "ForgetFactResponse": {
+ "properties": {
+ "uuid": { "type": "string", "title": "Uuid" },
+ "forgotten": { "type": "boolean", "title": "Forgotten" }
+ },
+ "type": "object",
+ "required": ["uuid", "forgotten"],
+ "title": "ForgetFactResponse"
+ },
"GlobalSearchResponse": {
"properties": {
"agents": {
@@ -21328,6 +21693,45 @@
"title": "MarketplaceListingCreator",
"description": "Creator information for a marketplace listing."
},
+ "MemoryFact": {
+ "properties": {
+ "uuid": { "type": "string", "title": "Uuid" },
+ "fact": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Fact"
+ },
+ "name": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Name"
+ },
+ "source": { "type": "string", "title": "Source" },
+ "target": { "type": "string", "title": "Target" },
+ "created_at": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Created At"
+ }
+ },
+ "type": "object",
+ "required": ["uuid", "source", "target"],
+ "title": "MemoryFact",
+ "description": "One live fact edge, as shown in the recent-memories list."
+ },
+ "MemoryFactListResponse": {
+ "properties": {
+ "expert_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Expert Id"
+ },
+ "items": {
+ "items": { "$ref": "#/components/schemas/MemoryFact" },
+ "type": "array",
+ "title": "Items"
+ }
+ },
+ "type": "object",
+ "required": ["items"],
+ "title": "MemoryFactListResponse"
+ },
"MemoryForgetCandidatesResponse": {
"properties": {
"type": {
@@ -21432,6 +21836,21 @@
"title": "MemoryOverview",
"description": "Counts surfaced in the visualizer's header strip."
},
+ "MemoryScopeOverview": {
+ "properties": {
+ "expert_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Expert Id"
+ },
+ "facts": { "type": "integer", "title": "Facts" },
+ "entities": { "type": "integer", "title": "Entities" },
+ "episodes": { "type": "integer", "title": "Episodes" }
+ },
+ "type": "object",
+ "required": ["facts", "entities", "episodes"],
+ "title": "MemoryScopeOverview",
+ "description": "Counts for one memory scope, shown on the settings page and in the\nerase-confirmation dialog."
+ },
"MemorySearchResponse": {
"properties": {
"type": {