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): add chat pinning to copilot sidebar (#13453)

Abhimanyu Yadavebc382e78df7
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index decdf0bf8a..d4121a1055 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -34,6 +34,7 @@ from backend.copilot.model import (
get_chat_session_metadata,
get_or_create_builder_session,
get_user_sessions,
+ update_session_pinned,
update_session_title,
)
from backend.copilot.pending_message_helpers import (
@@ -333,6 +334,7 @@ class SessionSummaryResponse(BaseModel):
chat_status: str = "idle"
is_processing: bool
source_platform: str | None = None
+ is_pinned: bool = False
class ListSessionsResponse(BaseModel):
@@ -363,6 +365,12 @@ class UpdateSessionTitleRequest(BaseModel):
return stripped
+class UpdateSessionPinnedRequest(BaseModel):
+ """Request model for pinning/unpinning a session."""
+
+ is_pinned: bool
+
+
# ========== Routes ==========
@@ -379,7 +387,7 @@ async def list_sessions(
List chat sessions for the authenticated user.
Returns a paginated list of chat sessions belonging to the current user,
- ordered by most recently updated.
+ with pinned sessions first and most-recently-updated as the tiebreaker.
Args:
user_id: The authenticated user's ID.
@@ -426,6 +434,7 @@ async def list_sessions(
chat_status=session.chat_status,
is_processing=session.session_id in processing_set,
source_platform=session.metadata.source_platform,
+ is_pinned=session.is_pinned,
)
for session in sessions
],
@@ -593,6 +602,44 @@ async def update_session_title_route(
return {"status": "ok"}
+ "/sessions/{session_id}/pinned",
+ summary="Update session pinned",
+ dependencies=[Security(auth.requires_user)],
+ status_code=200,
+ responses={404: {"description": "Session not found or access denied"}},
+)
+async def update_session_pinned_route(
+ session_id: str,
+ request: UpdateSessionPinnedRequest,
+ user_id: Annotated[str, Security(auth.get_user_id)],
+) -> dict:
+ """
+ Pin or unpin a chat session.
+
+ Pinned sessions surface at the top of the user's sidebar list ahead of
+ unpinned ones, regardless of recency.
+
+ Args:
+ session_id: The session ID to update.
+ request: Request body containing the new pin state.
+ user_id: The authenticated user's ID.
+
+ Returns:
+ dict: Status of the update.
+
+ Raises:
+ HTTPException: 404 if session not found or not owned by user.
+ """
+ success = await update_session_pinned(session_id, user_id, request.is_pinned)
+ if not success:
+ raise HTTPException(
+ status_code=404,
+ detail=f"Session {session_id} not found or access denied",
+ )
+ return {"status": "ok"}
+
+
@router.get(
"/sessions/{session_id}",
)
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 b07229523c..c22a07ce49 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -128,6 +128,73 @@ def test_update_title_not_found(
assert response.status_code == 404
+# ─── Update pinned ────────────────────────────────────────────────────
+
+
+def _mock_update_session_pinned(
+ mocker: pytest_mock.MockerFixture, *, success: bool = True
+):
+ """Mock update_session_pinned."""
+ return mocker.patch(
+ "backend.api.features.chat.routes.update_session_pinned",
+ new_callable=AsyncMock,
+ return_value=success,
+ )
+
+
+def test_update_pinned_success(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mock_update = _mock_update_session_pinned(mocker, success=True)
+
+ response = client.patch(
+ "/sessions/sess-1/pinned",
+ json={"is_pinned": True},
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {"status": "ok"}
+ mock_update.assert_called_once_with("sess-1", test_user_id, True)
+
+
+def test_update_pinned_unpin(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mock_update = _mock_update_session_pinned(mocker, success=True)
+
+ response = client.patch(
+ "/sessions/sess-1/pinned",
+ json={"is_pinned": False},
+ )
+
+ assert response.status_code == 200
+ mock_update.assert_called_once_with("sess-1", test_user_id, False)
+
+
+def test_update_pinned_missing_field_rejected(
+ test_user_id: str,
+) -> None:
+ response = client.patch("/sessions/sess-1/pinned", json={})
+
+ assert response.status_code == 422
+
+
+def test_update_pinned_not_found(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ _mock_update_session_pinned(mocker, success=False)
+
+ response = client.patch(
+ "/sessions/sess-1/pinned",
+ json={"is_pinned": True},
+ )
+
+ assert response.status_code == 404
+
+
# ─── file_ids Pydantic validation ─────────────────────────────────────
@@ -1148,6 +1215,7 @@ def _make_session_info(
session_id: str = "sess-1",
title: str | None = "Test",
source_platform: str | None = None,
+ is_pinned: bool = False,
):
"""Build a minimal ChatSessionInfo-like mock."""
from backend.copilot.model import ChatSessionInfo, ChatSessionMetadata
@@ -1160,6 +1228,7 @@ def _make_session_info(
started_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
metadata=ChatSessionMetadata(source_platform=source_platform),
+ is_pinned=is_pinned,
)
@@ -1219,6 +1288,32 @@ def test_list_sessions_returns_source_platform(
assert response.json()["sessions"][0]["source_platform"] == "discord"
+def test_list_sessions_returns_is_pinned(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ session = _make_session_info("sess-pinned", is_pinned=True)
+ mocker.patch(
+ "backend.api.features.chat.routes.get_user_sessions",
+ new_callable=AsyncMock,
+ return_value=([session], 1),
+ )
+ mock_redis = MagicMock()
+ mock_pipe = MagicMock()
+ mock_pipe.hget = MagicMock(return_value=None)
+ mock_pipe.execute = AsyncMock(return_value=["done"])
+ mock_redis.pipeline = MagicMock(return_value=mock_pipe)
+ mocker.patch(
+ "backend.api.features.chat.routes.get_redis_async",
+ new_callable=AsyncMock,
+ return_value=mock_redis,
+ )
+
+ response = client.get("/sessions")
+
+ assert response.status_code == 200
+ assert response.json()["sessions"][0]["is_pinned"] is True
+
+
def test_list_sessions_marks_running_as_processing(
mocker: pytest_mock.MockerFixture,
) -> None:
diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.py
index 1fe0e11510..40835cb778 100644
--- a/autogpt_platform/backend/backend/copilot/db.py
+++ b/autogpt_platform/backend/backend/copilot/db.py
@@ -329,6 +329,29 @@ async def update_chat_session_title(
return result > 0
+async def update_chat_session_pinned(
+ session_id: str,
+ user_id: str,
+ is_pinned: bool,
+) -> bool:
+ """Pin or unpin a chat session, scoped to the owning user.
+
+ Always filters by (session_id, user_id) so callers cannot mutate another
+ user's session even when they know the session_id. Does not bump
+ ``updatedAt`` — pinning is not an activity event and should not reorder
+ the session within its pin bucket.
+
+ Returns True if a row was updated, False otherwise (session not found or
+ wrong user).
+ """
+ where: ChatSessionWhereInput = {"id": session_id, "userId": user_id}
+ result = await PrismaChatSession.prisma().update_many(
+ where=where,
+ data={"isPinned": is_pinned},
+ )
+ return result > 0
+
+
async def add_chat_message(
session_id: str,
role: str,
@@ -539,7 +562,7 @@ async def get_user_chat_sessions(
where["title"] = {"contains": title_contains, "mode": "insensitive"}
prisma_sessions = await PrismaChatSession.prisma().find_many(
where=where,
- order={"updatedAt": "desc"},
+ order=[{"isPinned": "desc"}, {"updatedAt": "desc"}],
take=limit,
skip=offset,
)
diff --git a/autogpt_platform/backend/backend/copilot/db_test.py b/autogpt_platform/backend/backend/copilot/db_test.py
index 83a815c803..ca4777feea 100644
--- a/autogpt_platform/backend/backend/copilot/db_test.py
+++ b/autogpt_platform/backend/backend/copilot/db_test.py
@@ -13,7 +13,9 @@ from prisma.models import ChatSession as PrismaChatSession
from backend.copilot.db import (
PaginatedMessages,
get_chat_messages_paginated,
+ get_user_chat_sessions,
set_turn_duration,
+ update_chat_session_pinned,
update_message_content_by_sequence,
)
from backend.copilot.model import ChatMessage as CopilotChatMessage
@@ -62,6 +64,7 @@ def _make_session(
title=None,
metadata={},
chatStatus="idle",
+ isPinned=False,
# Sharing fields added by the chat-sharing PR — even with
# ``model_construct`` Pydantic v2 still validates required
# non-optional columns, so the mock needs them explicitly.
@@ -618,6 +621,53 @@ async def test_update_message_content_by_sequence_sanitizes_content():
)
+# ---------- update_chat_session_pinned ----------
+
+
+async def test_update_chat_session_pinned_success():
+ """Returns True and writes isPinned scoped to (session_id, user_id)."""
+ update_many = AsyncMock(return_value=1)
+ with patch.object(
+ PrismaChatSession, "prisma", return_value=AsyncMock(update_many=update_many)
+ ):
+ result = await update_chat_session_pinned("sess-1", "user-abc", True)
+
+ assert result is True
+ update_many.assert_called_once_with(
+ where={"id": "sess-1", "userId": "user-abc"},
+ data={"isPinned": True},
+ )
+
+
+async def test_update_chat_session_pinned_not_found():
+ """Returns False when no row matches (session missing or wrong user)."""
+ update_many = AsyncMock(return_value=0)
+ with patch.object(
+ PrismaChatSession, "prisma", return_value=AsyncMock(update_many=update_many)
+ ):
+ result = await update_chat_session_pinned("sess-1", "user-abc", False)
+
+ assert result is False
+
+
+# ---------- get_user_chat_sessions ordering ----------
+
+
+async def test_get_user_chat_sessions_orders_pinned_first():
+ """Pinned sessions must be ordered ahead of unpinned, then by recency."""
+ find_many = AsyncMock(return_value=[])
+ with patch.object(
+ PrismaChatSession, "prisma", return_value=AsyncMock(find_many=find_many)
+ ):
+ await get_user_chat_sessions("user-abc", limit=10, offset=0)
+
+ order = find_many.call_args.kwargs["order"]
+ assert order == [{"isPinned": "desc"}, {"updatedAt": "desc"}]
+
+
# NOTE: previously this file had a separate suite for ``db.get_chat_session``
# (windowed eager-load). That function was removed in favour of going through
# ``get_chat_messages_paginated`` directly — see ``model._get_session_from_db``.
@@ -661,6 +711,7 @@ async def test_list_chat_sessions_by_status_returns_app_models_oldest_first() ->
metadata="{}",
totalPromptTokens=0,
totalCompletionTokens=0,
+ isPinned=False,
isShared=False,
shareToken=None,
sharedAt=None,
@@ -678,6 +729,7 @@ async def test_list_chat_sessions_by_status_returns_app_models_oldest_first() ->
metadata="{}",
totalPromptTokens=0,
totalCompletionTokens=0,
+ isPinned=False,
isShared=False,
shareToken=None,
sharedAt=None,
diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.py
index 8836cd008b..f650317fe9 100644
--- a/autogpt_platform/backend/backend/copilot/model.py
+++ b/autogpt_platform/backend/backend/copilot/model.py
@@ -198,6 +198,8 @@ class ChatSessionInfo(BaseModel):
metadata: ChatSessionMetadata = ChatSessionMetadata()
# Session lifecycle: "idle" | "queued" | "running" (see CHAT_STATUS_*).
chat_status: str = "idle"
+ # Whether the user has pinned this session to the top of the sidebar.
+ is_pinned: bool = False
@property
def dry_run(self) -> bool:
@@ -247,6 +249,7 @@ class ChatSessionInfo(BaseModel):
successful_agent_schedules=successful_agent_schedules,
metadata=metadata,
chat_status=prisma_session.chatStatus,
+ is_pinned=prisma_session.isPinned,
)
@@ -744,15 +747,19 @@ async def upsert_chat_session(
db_error = e
# Save to cache (best-effort, even if DB failed).
- # Title updates (update_session_title) run *outside* this lock because
- # they only touch the title field, not messages. So a concurrent rename
- # or auto-title may have written a newer title to Redis while this
- # upsert was in progress. Always prefer the cached title to avoid
- # overwriting it with the stale in-memory copy.
+ # Title (update_session_title) and pin state (update_session_pinned)
+ # are mutated *outside* this lock — they only touch their single field,
+ # not messages — so a concurrent rename, auto-title, or pin/unpin may
+ # have written a newer value to Redis while this upsert was in progress.
+ # Always prefer the cached title/pin to avoid reverting it with the
+ # stale in-memory copy.
try:
existing_cached = await _get_session_from_cache(session.session_id)
- if existing_cached and existing_cached.title:
- session = session.model_copy(update={"title": existing_cached.title})
+ if existing_cached:
+ updates: dict[str, Any] = {"is_pinned": existing_cached.is_pinned}
+ if existing_cached.title:
+ updates["title"] = existing_cached.title
+ session = session.model_copy(update=updates)
await cache_chat_session(session)
except Exception as e:
# If DB succeeded but cache failed, raise cache error
@@ -1213,6 +1220,46 @@ async def update_session_title(
return False
+async def update_session_pinned(
+ session_id: str,
+ user_id: str,
+ is_pinned: bool,
+) -> bool:
+ """Pin or unpin a chat session, scoped to the owning user.
+
+ Lightweight operation that doesn't touch messages, mirroring
+ ``update_session_title``. Keeps the Redis cache in sync so the
+ sidebar reflects the change without waiting on a cache invalidation.
+
+ Args:
+ session_id: The session ID to update.
+ user_id: Owning user — the DB query filters on this.
+ is_pinned: New pin state.
+
+ Returns:
+ True if updated successfully, False only for the real not-found / wrong-user
+ case. Unexpected DB/runtime failures propagate so the route surfaces a 5xx
+ rather than masking them as a 404.
+ """
+ updated = await chat_db().update_chat_session_pinned(session_id, user_id, is_pinned)
+ if not updated:
+ return False
+
+ # Cache refresh is best-effort — a cache failure must not fail the request,
+ # the DB write already succeeded.
+ try:
+ cached = await _get_session_from_cache(session_id)
+ if cached:
+ cached.is_pinned = is_pinned
+ await cache_chat_session(cached)
+ except Exception as e:
+ logger.warning(
+ f"Cache pin update failed for session {session_id} (non-critical): {e}"
+ )
+
+ return True
+
+
# ==================== Chat session locks ==================== #
diff --git a/autogpt_platform/backend/backend/copilot/model_test.py b/autogpt_platform/backend/backend/copilot/model_test.py
index b404d74dcb..8684b7995a 100644
--- a/autogpt_platform/backend/backend/copilot/model_test.py
+++ b/autogpt_platform/backend/backend/copilot/model_test.py
@@ -78,6 +78,29 @@ async def test_chatsession_redis_storage(setup_test_user, test_user_id):
assert s2 == s
[email protected](loop_scope="session")
+async def test_upsert_preserves_pinned_set_concurrently(setup_test_user, test_user_id):
+ """A pin written out-of-band (update_session_pinned) must survive a later
+ upsert that carries a stale in-memory is_pinned=False (e.g. end-of-stream
+ save), mirroring how the cached title is preserved."""
+ from .model import update_session_pinned
+
+ s = ChatSession.new(user_id=test_user_id, dry_run=False)
+ s.messages = messages
+ s = await upsert_chat_session(s)
+
+ # Pin out-of-band (writes both DB and cache), as the PATCH route does.
+ assert await update_session_pinned(s.session_id, test_user_id, True) is True
+
+ # End-of-stream upsert with a stale in-memory copy that never saw the pin.
+ s.is_pinned = False
+ await upsert_chat_session(s)
+
+ reloaded = await get_chat_session(s.session_id, test_user_id)
+ assert reloaded is not None
+ assert reloaded.is_pinned is True
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_chatsession_redis_storage_user_id_mismatch(
setup_test_user, test_user_id
diff --git a/autogpt_platform/backend/backend/copilot/sharing/db_test.py b/autogpt_platform/backend/backend/copilot/sharing/db_test.py
index 3a92842a4a..b9bd8bdbb6 100644
--- a/autogpt_platform/backend/backend/copilot/sharing/db_test.py
+++ b/autogpt_platform/backend/backend/copilot/sharing/db_test.py
@@ -55,6 +55,7 @@ def _mock_session(*, auto_share_executions: bool = False) -> PrismaChatSession:
totalCompletionTokens=0,
metadata={},
chatStatus="idle",
+ isPinned=False,
isShared=True,
shareToken="token-A",
sharedAt=now,
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index ec072d9da3..ec4a7be142 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -444,6 +444,7 @@ class DatabaseManager(AppService):
update_tool_message_content = _(chat_db.update_tool_message_content)
update_message_content_by_sequence = _(chat_db.update_message_content_by_sequence)
update_chat_session_title = _(chat_db.update_chat_session_title)
+ update_chat_session_pinned = _(chat_db.update_chat_session_pinned)
set_turn_duration = _(chat_db.set_turn_duration)
# ChatSession lifecycle primitives. Three functions cover the
# cap-count + cross-session queue (count/list/transition).
@@ -701,6 +702,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
update_tool_message_content = d.update_tool_message_content
update_message_content_by_sequence = d.update_message_content_by_sequence
update_chat_session_title = d.update_chat_session_title
+ update_chat_session_pinned = d.update_chat_session_pinned
set_turn_duration = d.set_turn_duration
count_chat_sessions_by_status = d.count_chat_sessions_by_status
list_chat_sessions_by_status = d.list_chat_sessions_by_status
diff --git a/autogpt_platform/backend/migrations/20260630120000_add_chat_session_is_pinned/migration.sql b/autogpt_platform/backend/migrations/20260630120000_add_chat_session_is_pinned/migration.sql
new file mode 100644
index 0000000000..95be76c317
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260630120000_add_chat_session_is_pinned/migration.sql
@@ -0,0 +1,4 @@
+-- Add a pin flag to ChatSession so users can pin chats to the top of the
+-- sidebar list. Defaults to false so existing sessions stay unpinned.
+-- AlterTable
+ALTER TABLE "ChatSession" ADD COLUMN "isPinned" BOOLEAN NOT NULL DEFAULT false;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 84bebdb4a4..49113ef819 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -283,6 +283,11 @@ model ChatSession {
Messages ChatMessage[]
+ // When true, the session is pinned to the top of the user's sidebar
+ // list, surfacing ahead of unpinned sessions regardless of recency.
+ // Mirrors the LibraryAgent.isFavorite pattern.
+ isPinned Boolean @default(false)
+
// Sharing fields — mirrors AgentGraphExecution sharing
isShared Boolean @default(false)
shareToken String? @unique
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSessionBlock/ChatSessionBlock.stories.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSessionBlock/ChatSessionBlock.stories.tsx
index ab0e80830a..3f21c13b53 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSessionBlock/ChatSessionBlock.stories.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSessionBlock/ChatSessionBlock.stories.tsx
@@ -91,6 +91,14 @@ export const LinearCompleted: Story = {
},
};
+export const Pinned: Story = {
+ args: {
+ title: "Pinned project plan",
+ updatedAt: daysAgo(2),
+ showPinned: true,
+ },
+};
+
export const PlatformMatrix: Story = {
render: () => (
<div className="space-y-1">
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSessionBlock/ChatSessionBlock.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSessionBlock/ChatSessionBlock.tsx
index 734b700c2e..08b16bd5cc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSessionBlock/ChatSessionBlock.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSessionBlock/ChatSessionBlock.tsx
@@ -6,6 +6,7 @@ import {
CheckCircleIcon,
CircleNotchIcon,
HourglassIcon,
+ PushPinIcon,
} from "@phosphor-icons/react";
import type { ReactNode } from "react";
import { ChatOriginIcon } from "../ChatOriginIcon/ChatOriginIcon";
@@ -19,6 +20,7 @@ interface Props {
chatStatus?: string | null;
showProcessing?: boolean;
showCompleted?: boolean;
+ showPinned?: boolean;
className?: string;
}
@@ -56,6 +58,7 @@ export function ChatSessionBlock({
chatStatus,
showProcessing = false,
showCompleted = false,
+ showPinned = false,
className,
}: Props) {
const displayTitle = title || "Untitled chat";
@@ -77,6 +80,14 @@ export function ChatSessionBlock({
</Text>
</div>
<div className="flex items-center gap-1.5">
+ {showPinned ? (
+ <PushPinIcon
+ aria-label="Pinned"
+ data-testid="session-pinned-indicator"
+ className="h-3 w-3 shrink-0 text-neutral-400"
+ weight="fill"
+ />
+ ) : null}
<Text variant="small" className="text-neutral-400">
{formatDate(updatedAt)}
</Text>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
index abad9e0cd9..9546720844 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
@@ -1,6 +1,7 @@
"use client";
import {
getV2GetSession,
+ usePatchV2UpdateSessionPinned,
usePatchV2UpdateSessionTitle,
} from "@/app/api/__generated__/endpoints/chat/chat";
import { Button } from "@/components/atoms/Button/Button";
@@ -22,6 +23,7 @@ import {
useSidebar,
} from "@/components/ui/sidebar";
import { cn } from "@/lib/utils";
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import {
CircleNotch,
@@ -32,6 +34,8 @@ import {
PencilSimpleIcon,
PlusCircleIcon,
PlusIcon,
+ PushPinIcon,
+ PushPinSlashIcon,
ShareNetworkIcon,
TrashIcon,
} from "@phosphor-icons/react";
@@ -95,6 +99,31 @@ export function ChatSidebar() {
const renameInputRef = useRef<HTMLInputElement>(null);
const renameCancelledRef = useRef(false);
const chatSharingEnabled = useGetFlag(Flag.CHAT_SHARING);
+ const isPinningEnabled = useGetFlag(Flag.CHAT_PINNING);
+
+ const { mutate: setSessionPinned } = usePatchV2UpdateSessionPinned({
+ mutation: {
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ queryKey: SESSION_LIST_QUERY_KEY,
+ });
+ },
+ onError: (error) => {
+ const description =
+ error instanceof ApiError
+ ? ((error.response as { detail?: string } | undefined)?.detail ??
+ error.message)
+ : error instanceof Error
+ ? error.message
+ : "An error occurred";
+ toast({
+ title: "Failed to update chat",
+ description,
+ variant: "destructive",
+ });
+ },
+ },
+ });
const { mutate: renameSession } = usePatchV2UpdateSessionTitle({
mutation: {
@@ -177,6 +206,11 @@ export function ChatSidebar() {
requestDelete(id, title);
}
+ function handlePinClick(e: React.MouseEvent, id: string, isPinned: boolean) {
+ e.stopPropagation();
+ setSessionPinned({ sessionId: id, data: { is_pinned: !isPinned } });
+ }
+
async function handleExportClick(
e: React.MouseEvent,
id: string,
@@ -402,6 +436,7 @@ export function ChatSidebar() {
}
updatedAt={session.updated_at}
sourcePlatform={session.source_platform}
+ showPinned={isPinningEnabled && !!session.is_pinned}
isActive={session.id === sessionId}
chatStatus={session.chat_status}
showProcessing={
@@ -447,6 +482,29 @@ export function ChatSidebar() {
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
+ {isPinningEnabled && (
+ <DropdownMenuItem
+ onClick={(e) =>
+ handlePinClick(
+ e,
+ session.id,
+ !!session.is_pinned,
+ )
+ }
+ >
+ {session.is_pinned ? (
+ <>
+ <PushPinSlashIcon className="mr-2 h-4 w-4" />
+ Unpin chat
+ </>
+ ) : (
+ <>
+ <PushPinIcon className="mr-2 h-4 w-4" />
+ Pin chat
+ </>
+ )}
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
onClick={(e) =>
handleRenameClick(e, session.id, session.title)
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx
index eb9695b4c3..4f7fd21ee6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx
@@ -37,7 +37,8 @@ vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
>();
return {
...actual,
- useGetFlag: (flag: string) => flag === "chat-search",
+ useGetFlag: (flag: string) =>
+ flag === "chat-search" || flag === "chat-pinning",
};
});
@@ -284,6 +285,80 @@ describe("ChatSidebar — chat_status indicators", () => {
});
});
+describe("ChatSidebar — pinning", () => {
+ afterEach(() => {
+ server.resetHandlers();
+ });
+
+ async function openMenuFor(title: string) {
+ const sessionRow = (await screen.findByText(title)).closest("div.group");
+ if (!sessionRow) throw new Error(`row not found for ${title}`);
+ const moreButton = within(sessionRow as HTMLElement).getByRole("button", {
+ name: /more actions/i,
+ });
+ fireEvent.pointerDown(moreButton, { button: 0 });
+ }
+
+ it("pins an unpinned session via the dropdown", async () => {
+ let pinnedBody: { is_pinned?: boolean } | null = null;
+ server.use(
+ getGetV2ListSessionsMockHandler200({
+ sessions: [
+ {
+ id: "s1",
+ title: "Unpinned chat",
+ is_processing: false,
+ is_pinned: false,
+ created_at: "2025-01-01T00:00:00Z",
+ updated_at: "2025-01-01T00:00:00Z",
+ },
+ ],
+ total: 1,
+ }),
+ http.patch("*/api/chat/sessions/:id/pinned", async ({ request }) => {
+ pinnedBody = (await request.json()) as { is_pinned: boolean };
+ return HttpResponse.json({ status: "ok" });
+ }),
+ );
+ renderSidebar();
+
+ await openMenuFor("Unpinned chat");
+ const pinItem = await screen.findByRole("menuitem", { name: /pin chat/i });
+ fireEvent.click(pinItem);
+
+ await vi.waitFor(() => {
+ expect(pinnedBody).toEqual({ is_pinned: true });
+ });
+ });
+
+ it("offers Unpin and a pinned indicator for pinned sessions", async () => {
+ server.use(
+ getGetV2ListSessionsMockHandler200({
+ sessions: [
+ {
+ id: "s1",
+ title: "Pinned chat",
+ is_processing: false,
+ is_pinned: true,
+ created_at: "2025-01-01T00:00:00Z",
+ updated_at: "2025-01-01T00:00:00Z",
+ },
+ ],
+ total: 1,
+ }),
+ );
+ renderSidebar();
+
+ await screen.findByText("Pinned chat");
+ expect(screen.getByTestId("session-pinned-indicator")).toBeDefined();
+
+ await openMenuFor("Pinned chat");
+ expect(
+ await screen.findByRole("menuitem", { name: /unpin chat/i }),
+ ).toBeDefined();
+ });
+});
+
describe("ChatSidebar — pagination", () => {
afterEach(() => {
server.resetHandlers();
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 74144b3e9e..98235ad2f2 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -3294,7 +3294,7 @@
"get": {
"tags": ["v2", "chat", "chat"],
"summary": "List Sessions",
- "description": "List chat sessions for the authenticated user.\n\nReturns a paginated list of chat sessions belonging to the current user,\nordered by most recently updated.\n\nArgs:\n user_id: The authenticated user's ID.\n limit: Maximum number of sessions to return (1-100).\n offset: Number of sessions to skip for pagination.\n\nReturns:\n ListSessionsResponse: List of session summaries and total count.",
+ "description": "List chat sessions for the authenticated user.\n\nReturns a paginated list of chat sessions belonging to the current user,\nwith pinned sessions first and most-recently-updated as the tiebreaker.\n\nArgs:\n user_id: The authenticated user's ID.\n limit: Maximum number of sessions to return (1-100).\n offset: Number of sessions to skip for pagination.\n\nReturns:\n ListSessionsResponse: List of session summaries and total count.",
"operationId": "getV2ListSessions",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -3663,6 +3663,59 @@
}
}
},
+ "/api/chat/sessions/{session_id}/pinned": {
+ "patch": {
+ "tags": ["v2", "chat", "chat"],
+ "summary": "Update session pinned",
+ "description": "Pin or unpin a chat session.\n\nPinned sessions surface at the top of the user's sidebar list ahead of\nunpinned ones, regardless of recency.\n\nArgs:\n session_id: The session ID to update.\n request: Request body containing the new pin state.\n user_id: The authenticated user's ID.\n\nReturns:\n dict: Status of the update.\n\nRaises:\n HTTPException: 404 if session not found or not owned by user.",
+ "operationId": "patchV2Update session pinned",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Session Id" }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateSessionPinnedRequest"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "additionalProperties": true,
+ "title": "Response Patchv2Update Session Pinned"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "404": { "description": "Session not found or access denied" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/chat/sessions/{session_id}/share": {
"delete": {
"tags": ["v2", "chat", "share", "chat", "share"],
@@ -19284,6 +19337,11 @@
"source_platform": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Source Platform"
+ },
+ "is_pinned": {
+ "type": "boolean",
+ "title": "Is Pinned",
+ "default": false
}
},
"type": "object",
@@ -21512,6 +21570,15 @@
"required": ["permissions"],
"title": "UpdatePermissionsRequest"
},
+ "UpdateSessionPinnedRequest": {
+ "properties": {
+ "is_pinned": { "type": "boolean", "title": "Is Pinned" }
+ },
+ "type": "object",
+ "required": ["is_pinned"],
+ "title": "UpdateSessionPinnedRequest",
+ "description": "Request model for pinning/unpinning a session."
+ },
"UpdateSessionTitleRequest": {
"properties": { "title": { "type": "string", "title": "Title" } },
"type": "object",
diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
index b2a5c009d5..6ba7455cea 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
@@ -19,6 +19,7 @@ export enum Flag {
CHAT_SHARING = "chat-sharing",
AUTOGPT_NEW_LAYOUT = "autogpt-new-layout",
CHAT_WORKSPACE_FILES = "chat-workspace-files",
+ CHAT_PINNING = "chat-pinning",
// Graphiti memory + dream-system gates. Mirror of the backend
// ``Flag`` enum in ``backend/util/feature_flag.py``. Frontend reads
// them when memory/dream-related UI surfaces ship (P6+ on the
@@ -50,6 +51,7 @@ const defaultFlags = {
[Flag.CHAT_SHARING]: false,
[Flag.AUTOGPT_NEW_LAYOUT]: false,
[Flag.CHAT_WORKSPACE_FILES]: false,
+ [Flag.CHAT_PINNING]: false,
[Flag.GRAPHITI_MEMORY]: false,
[Flag.GRAPHITI_COMMUNITIES_ENABLED]: false,
[Flag.DREAM_PASS_ENABLED]: false,
@@ -104,6 +106,8 @@ function readEnvOverride(flag: Flag): string | undefined {
return process.env.NEXT_PUBLIC_FORCE_FLAG_AUTOGPT_NEW_LAYOUT;
case Flag.CHAT_WORKSPACE_FILES:
return process.env.NEXT_PUBLIC_FORCE_FLAG_CHAT_WORKSPACE_FILES;
+ case Flag.CHAT_PINNING:
+ return process.env.NEXT_PUBLIC_FORCE_FLAG_CHAT_PINNING;
case Flag.GRAPHITI_MEMORY:
return process.env.NEXT_PUBLIC_FORCE_FLAG_GRAPHITI_MEMORY;
case Flag.GRAPHITI_COMMUNITIES_ENABLED: