Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(business-knowledge): paginate playground chat history (#108112)

posthog[bot]905fa65ba00e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index db90a87537cd..99b4f8e39c13 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10315,21 +10315,21 @@ snapshots:
scenes-app-batchexports--runs-with-data--light:
hash: v1.k794b7964.4c1646577dc53efffd814b1a2e723f9da6b10d3641e979f48c5d0447859e2348.fkHuUw1l_9c3rJKSi467jx-6Nv81nNp-PjeRmsgU7l0
scenes-app-business-knowledge-playground--chat-citations--dark:
- hash: v1.k794b7964.46287a4667d6a7977a23193db30e3042377ebc7e988cd5eccd8a1ac411d45966.OZvEKplY375_EkYnxSBg_hWz-HmkWE-3n83RW4gcPe0
+ hash: v1.k794b7964.f33230cec1a880036c1e49d2b44ab0b92b6d15c3106f685a13d515ab8ac4230f.CxWKgd9M6PoAIuzKR5lbU-qVG-DdrqvbtoVL-Nd_GHs
scenes-app-business-knowledge-playground--chat-citations--light:
- hash: v1.k794b7964.51499b6453006544ad1dea90bb84c7d1006aa68c3579f7d43a24eefced66cd34.SDbrud1AhjhV6lNIqj2G2jKfOaIWrYvLla6q5qE7-pg
+ hash: v1.k794b7964.c0228cb7c4b803c2416f6502715cb216814450a56854f265193159c17f5cd609.ojftUVMGwKclbivbpyHoBGMHXUGxBYyLpdPbILKohoU
scenes-app-business-knowledge-playground--narrow-scene--dark:
hash: v1.k794b7964.214dcbfdd83528acbf86aba54eaa5659f3cac634d565755abfb81341bfba069c.nOL5OGbm21fzE_iPcc8BcJEzAtR8bKLKwrGnuXWpUmk
scenes-app-business-knowledge-playground--narrow-scene--light:
hash: v1.k794b7964.aa4e94c16ddd63c4a423281080484d03c19260dce42e1ddc2aa91d1516bde768._4DWwyNePgLqaTkf-3LWkLJ2aB-czJUvKynzdVnJGls
scenes-app-business-knowledge-playground--new-chat--dark:
- hash: v1.k794b7964.5204ba012e17ab3cb7d32cce00fadc82ca73d186071ce944c7bea604b9a0e018.xYIFSiA8hbd2dgrd2obg6v-zKOgMwwfsZ0cXDjePRG8
+ hash: v1.k794b7964.1f7ba14e1b2c2a59a563b3591a034f38a70c94c12505190a640beb876a878ee7.6k-euXTp7SPHOXEZByK0EItpGgea-OHOvDzYBMSSUu0
scenes-app-business-knowledge-playground--new-chat--light:
- hash: v1.k794b7964.62cf0349d8e1f4b1ceff4bab4c0065a605bfd6c7c1850f9a9250e9f362901fcc.owuQiZCglMK7214KVp8j2lGQqymA4i3lPcpyxr8uObI
+ hash: v1.k794b7964.d69464ff20aa6ae79fa690148636399857433ab133d3236e9a062a44df1268f4.GPW6dBR2epPBBNh4gc778wF-m9hrM5kH4pOS3L5Lb-I
scenes-app-business-knowledge-playground--saved-chat--dark:
- hash: v1.k794b7964.0071e299896e5467fc857e07d2000a5e47f73f38a91d6cc0333e18f461d5e87d.FbrwmsH2s0A7Ntc2XjQrI6MxsLs5zAgNWBifTKxHwco
+ hash: v1.k794b7964.6063b33c3cd8393a9a73a54e4be227a7e53aed76f3eac9850a093cbce0b66b97.ujbDMWZEaoEuxCEVYTWswc2mRtzgROQmw5tlN-Yg2bE
scenes-app-business-knowledge-playground--saved-chat--light:
- hash: v1.k794b7964.bb58e075b37a593d5d4979d2427a5183a9c624ca67dbd977b861c5333068216b.FCVDwV8RrYTtl5_ccv2ZRNStH9BjDJDST3P_EqYHGPM
+ hash: v1.k794b7964.6c05d4d9d4edaa6ecfa78ae6569b02e8b7e822334a536f7019e711518aec2ff2.gOZ24rSpPgeoHTrnL5DkzjLsRhAL8l4qwn0BWVBNrjk
scenes-app-business-knowledge-playground--search-results--dark:
hash: v1.k794b7964.4a5178e5723a01554f25bbd2f8bcfbda830e1fe4d715638f8a8cd670a368bf7f.IsZTKk5J2yMk8-AoHT9SKgA_A8CuUqV_sGzr_HcIcf8
scenes-app-business-knowledge-playground--search-results--light:
diff --git a/products/business_knowledge/backend/api/playground.py b/products/business_knowledge/backend/api/playground.py
index cecbde215882..4214e830a6ac 100644
--- a/products/business_knowledge/backend/api/playground.py
+++ b/products/business_knowledge/backend/api/playground.py
@@ -13,6 +13,7 @@ from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.pagination import DefaultLimitOffsetPagination
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models.user import User
from posthog.permissions import APIScopePermission, PostHogFeatureFlagPermission
@@ -34,6 +35,11 @@ from .serializers import PlaygroundChatListSerializer, PlaygroundChatSerializer,
from .settings import CanonicalTeamTokenPermission
+class PlaygroundChatPagination(DefaultLimitOffsetPagination):
+ default_limit = 100
+ max_limit = 100
+
+
class BusinessKnowledgePlaygroundChatViewSet(
TeamAndOrgViewSetMixin,
mixins.DestroyModelMixin,
@@ -43,6 +49,7 @@ class BusinessKnowledgePlaygroundChatViewSet(
requires_resource_level_access = True
queryset = PlaygroundChat.objects.unscoped()
serializer_class = PlaygroundChatSerializer
+ pagination_class = PlaygroundChatPagination
permission_classes = [
IsAuthenticated,
APIScopePermission,
@@ -51,7 +58,6 @@ class BusinessKnowledgePlaygroundChatViewSet(
]
posthog_feature_flag = "product-business-knowledge"
throttle_classes = [BurstRateThrottle, SustainedRateThrottle]
- pagination_class = None
http_method_names = ["get", "post", "delete", "head", "options"]
@cached_property
@@ -80,12 +86,13 @@ class BusinessKnowledgePlaygroundChatViewSet(
)
def list(self, request: Request, **kwargs: Any) -> Response:
# A refused first question leaves an untitled chat behind.
+ page = self.paginate_queryset(self.get_queryset().exclude(title="").order_by("-updated_at", "-id"))
chats = serialize_playground_chat_list(
- self.get_queryset().exclude(title="").order_by("-updated_at"),
+ page or [],
team_id=self.team_id,
user_id=cast(User, request.user).id,
)
- return Response(PlaygroundChatListSerializer(chats, many=True).data)
+ return self.get_paginated_response(PlaygroundChatListSerializer(chats, many=True).data)
@extend_schema(
request=None,
diff --git a/products/business_knowledge/backend/tests/test_playground.py b/products/business_knowledge/backend/tests/test_playground.py
index e89e289857a8..5e48706daa7f 100644
--- a/products/business_knowledge/backend/tests/test_playground.py
+++ b/products/business_knowledge/backend/tests/test_playground.py
@@ -2,6 +2,7 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.test import SimpleTestCase
+from django.utils.timezone import now
from parameterized import parameterized
from rest_framework import status
@@ -56,7 +57,7 @@ class TestPlaygroundChatAPI(APIBaseTest):
other = User.objects.create_user(email="[email protected]", password="password", first_name="Other")
OrganizationMembership.objects.create(user=other, organization=self.organization)
self.client.force_login(other)
- assert self.client.get(self.url).json() == []
+ assert self.client.get(self.url).json()["results"] == []
assert self.client.get(chat_url).status_code == status.HTTP_404_NOT_FOUND
assert self.client.delete(chat_url).status_code == status.HTTP_404_NOT_FOUND
assert self.client.post(f"{chat_url}ask/", {"question": "Can I get a refund?"}, format="json").status_code == (
@@ -90,14 +91,14 @@ class TestPlaygroundChatAPI(APIBaseTest):
assert parallel.status_code == status.HTTP_201_CREATED, parallel.content
assert Task.objects.filter(origin_product=Task.OriginProduct.BUSINESS_KNOWLEDGE).count() == 2
- listed = {chat["id"]: chat["has_open_turn"] for chat in self.client.get(self.url).json()}
+ listed = {chat["id"]: chat["has_open_turn"] for chat in self.client.get(self.url).json()["results"]}
assert listed == {first["id"]: True, second["id"]: True}
assert untitled["id"] not in listed
TaskRun.objects.filter(task_id=started.json()["turns"][0]["task_id"]).update(
status=TaskRun.Status.COMPLETED, output={"reply": "Yes.", "sources": []}
)
- listed = {chat["id"]: chat["has_open_turn"] for chat in self.client.get(self.url).json()}
+ listed = {chat["id"]: chat["has_open_turn"] for chat in self.client.get(self.url).json()["results"]}
assert listed == {first["id"]: False, second["id"]: True}
follow_up = self.client.post(f"{self.url}{first['id']}/ask/", {"question": "And after 30 days?"}, format="json")
assert follow_up.status_code == status.HTTP_201_CREATED, follow_up.content
@@ -136,7 +137,7 @@ class TestPlaygroundChatAPI(APIBaseTest):
self.organization.save(update_fields=["is_ai_data_processing_approved"])
listed = self.client.get(self.url)
assert listed.status_code == status.HTTP_200_OK
- assert listed.json()[0]["id"] == chat["id"]
+ assert listed.json()["results"][0]["id"] == chat["id"]
still_readable = self.client.get(f"{self.url}{chat['id']}/")
assert still_readable.status_code == status.HTTP_200_OK
PlaygroundTurn.objects.unscoped().filter(chat_id=chat["id"]).update(run_id=None)
@@ -146,6 +147,36 @@ class TestPlaygroundChatAPI(APIBaseTest):
blocked = self.client.post(f"{self.url}{chat['id']}/ask/", {"question": "Another question"}, format="json")
assert blocked.status_code == status.HTTP_403_FORBIDDEN
+ def test_list_pages_by_most_recently_updated(self, _ff, _workflow) -> None:
+ chats = [self._create_chat() for _ in range(3)]
+ PlaygroundChat.objects.unscoped().filter(id__in=[chat["id"] for chat in chats]).update(title="Refunds")
+ PlaygroundChat.objects.unscoped().filter(id=chats[0]["id"]).update(title="Latest", updated_at=now())
+
+ first_page = self.client.get(self.url, {"limit": 2}).json()
+ second_page = self.client.get(first_page["next"]).json()
+
+ assert first_page["count"] == 3
+ assert first_page["results"][0]["id"] == chats[0]["id"]
+ listed = [chat["id"] for chat in first_page["results"] + second_page["results"]]
+ assert sorted(listed) == sorted(chat["id"] for chat in chats)
+ assert second_page["next"] is None
+
+ same_time = now()
+ PlaygroundChat.objects.unscoped().filter(id__in=[chat["id"] for chat in chats]).update(updated_at=same_time)
+ first_page = self.client.get(self.url, {"limit": 2}).json()
+ second_page = self.client.get(first_page["next"]).json()
+ assert [chat["id"] for chat in first_page["results"] + second_page["results"]] == sorted(
+ [chat["id"] for chat in chats], reverse=True
+ )
+
+ PlaygroundChat.objects.unscoped().bulk_create(
+ [PlaygroundChat(team=self.team, created_by=self.user, title="Another chat") for _ in range(101)]
+ )
+ capped_page = self.client.get(self.url, {"limit": 1000}).json()
+ assert capped_page["count"] == 104
+ assert len(capped_page["results"]) == 100
+ assert capped_page["next"] is not None
+
def test_delete_keeps_the_sandbox_task(self, _ff, _workflow) -> None:
chat = self._create_chat()
asked = self.client.post(f"{self.url}{chat['id']}/ask/", {"question": "Can I get a refund?"}, format="json")
diff --git a/products/business_knowledge/frontend/api.ts b/products/business_knowledge/frontend/api.ts
index e3cc428cb8ef..09691ec38e61 100644
--- a/products/business_knowledge/frontend/api.ts
+++ b/products/business_knowledge/frontend/api.ts
@@ -34,13 +34,15 @@ import type {
KnowledgeSearchResultApi,
KnowledgeSourceApi,
PlaygroundChatApi,
- PlaygroundChatListApi,
+ PaginatedPlaygroundChatListListApi,
SandboxQuestionApi,
KnowledgeSourceDocumentApi,
} from './generated/api.schemas'
export type { KnowledgeSourceApi as KnowledgeSourceDTOApi }
+export const PLAYGROUND_CHAT_PAGE_SIZE = 100
+
// TODO: replace with generated types once the backend exposes URL source serializers
export type RefreshIntervalValue = 'manual' | '1h' | '6h' | '24h' | '7d'
export type RefreshIntervalOption = { value: RefreshIntervalValue; label: string }
@@ -149,8 +151,11 @@ export async function deleteSource(id: string): Promise<void> {
await businessKnowledgeSourcesDestroy(String(getCurrentTeamId()), id)
}
-export async function listPlaygroundChats(): Promise<PlaygroundChatListApi[]> {
- return await businessKnowledgePlaygroundChatsList(String(getCurrentTeamId()))
+export async function listPlaygroundChats(offset: number = 0): Promise<PaginatedPlaygroundChatListListApi> {
+ return await businessKnowledgePlaygroundChatsList(String(getCurrentTeamId()), {
+ limit: PLAYGROUND_CHAT_PAGE_SIZE,
+ offset,
+ })
}
export async function createPlaygroundChat(): Promise<PlaygroundChatApi> {
diff --git a/products/business_knowledge/frontend/generated/api.schemas.ts b/products/business_knowledge/frontend/generated/api.schemas.ts
index 2802d8b8d524..c16ee69571c9 100644
--- a/products/business_knowledge/frontend/generated/api.schemas.ts
+++ b/products/business_knowledge/frontend/generated/api.schemas.ts
@@ -208,6 +208,15 @@ export interface PlaygroundChatListApi {
has_open_turn: boolean
}
+export interface PaginatedPlaygroundChatListListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: PlaygroundChatListApi[]
+}
+
/**
* * `running` - Running
* * `completed` - Completed
@@ -701,6 +710,17 @@ export type BusinessKnowledgeGapSuggestionsListParams = {
ticket_id?: string
}
+export type BusinessKnowledgePlaygroundChatsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type BusinessKnowledgeRepositoriesFileRetrieveParams = {
/**
* Require the repository to be in this library. Pass the same id used for document search and repository search. Omit to read any selected repository.
diff --git a/products/business_knowledge/frontend/generated/api.ts b/products/business_knowledge/frontend/generated/api.ts
index b95ea9a4ba3b..4651e4244e9b 100644
--- a/products/business_knowledge/frontend/generated/api.ts
+++ b/products/business_knowledge/frontend/generated/api.ts
@@ -12,6 +12,7 @@ import type {
BusinessKnowledgeDocumentsSearchListParams,
BusinessKnowledgeDocumentsWindowListParams,
BusinessKnowledgeGapSuggestionsListParams,
+ BusinessKnowledgePlaygroundChatsListParams,
BusinessKnowledgeRepositoriesFileRetrieveParams,
BusinessKnowledgeRepositoriesSearchParams,
BusinessKnowledgeSettingsApi,
@@ -32,11 +33,11 @@ import type {
PaginatedKnowledgeGapSuggestionListApi,
PaginatedKnowledgeSourceDocumentListApi,
PaginatedKnowledgeSourceListApi,
+ PaginatedPlaygroundChatListListApi,
PatchedBusinessKnowledgeSettingsUpdateApi,
PatchedKnowledgeLibraryUpdateApi,
PatchedUpdateTextSourceApi,
PlaygroundChatApi,
- PlaygroundChatListApi,
RepositoryConnectApi,
RepositoryConnectionApi,
RepositoryFileApi,
@@ -381,8 +382,23 @@ export const businessKnowledgeLibrariesDestroy = async (
})
}
-export const getBusinessKnowledgePlaygroundChatsListUrl = (projectId: string) => {
- return `/api/projects/${projectId}/business_knowledge/playground/chats/`
+export const getBusinessKnowledgePlaygroundChatsListUrl = (
+ projectId: string,
+ params?: BusinessKnowledgePlaygroundChatsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/business_knowledge/playground/chats/?${stringifiedParams}`
+ : `/api/projects/${projectId}/business_knowledge/playground/chats/`
}
/**
@@ -391,12 +407,16 @@ export const getBusinessKnowledgePlaygroundChatsListUrl = (projectId: string) =>
*/
export const businessKnowledgePlaygroundChatsList = async (
projectId: string,
+ params?: BusinessKnowledgePlaygroundChatsListParams,
options?: RequestInit
-): Promise<PlaygroundChatListApi[]> => {
- return apiMutator<PlaygroundChatListApi[]>(getBusinessKnowledgePlaygroundChatsListUrl(projectId), {
- ...options,
- method: 'GET',
- })
+): Promise<PaginatedPlaygroundChatListListApi> => {
+ return apiMutator<PaginatedPlaygroundChatListListApi>(
+ getBusinessKnowledgePlaygroundChatsListUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
}
export const getBusinessKnowledgePlaygroundChatsCreateUrl = (projectId: string) => {
diff --git a/products/business_knowledge/frontend/scenes/playground/BusinessKnowledgePlaygroundScene.stories.tsx b/products/business_knowledge/frontend/scenes/playground/BusinessKnowledgePlaygroundScene.stories.tsx
index 6b8b24569c96..d6f66992da6a 100644
--- a/products/business_knowledge/frontend/scenes/playground/BusinessKnowledgePlaygroundScene.stories.tsx
+++ b/products/business_knowledge/frontend/scenes/playground/BusinessKnowledgePlaygroundScene.stories.tsx
@@ -128,7 +128,12 @@ const meta: Meta = {
decorators: [
mswDecorator({
get: {
- '/api/projects/:team_id/business_knowledge/playground/chats/': [listedChat, olderChat],
+ '/api/projects/:team_id/business_knowledge/playground/chats/': {
+ count: 3,
+ next: '/api/projects/1/business_knowledge/playground/chats/?offset=2',
+ previous: null,
+ results: [listedChat, olderChat],
+ },
'/api/projects/:team_id/business_knowledge/playground/chats/:chatId/': chat,
'/api/projects/:team_id/business_knowledge/documents/search/': searchResults,
},
diff --git a/products/business_knowledge/frontend/scenes/playground/BusinessKnowledgePlaygroundScene.test.tsx b/products/business_knowledge/frontend/scenes/playground/BusinessKnowledgePlaygroundScene.test.tsx
index 513e23e5e0f0..2b8f08035fd1 100644
--- a/products/business_knowledge/frontend/scenes/playground/BusinessKnowledgePlaygroundScene.test.tsx
+++ b/products/business_knowledge/frontend/scenes/playground/BusinessKnowledgePlaygroundScene.test.tsx
@@ -49,6 +49,10 @@ const playgroundValues = {
chatId: 'chat-1',
chatSearch: '',
chatsLoading: false,
+ chatsError: null,
+ nextChatsOffset: null,
+ loadingMoreChats: false,
+ moreChatsError: null,
chats: [listedChat],
chatGroups: [{ label: 'Today', chats: [listedChat] }],
deletingChatId: null,
@@ -94,6 +98,7 @@ describe('BusinessKnowledgePlaygroundScene', () => {
newChat: jest.fn(),
deleteChat: jest.fn(),
setChatSearch: jest.fn(),
+ loadMoreChats: jest.fn(),
})
})
@@ -126,4 +131,49 @@ describe('BusinessKnowledgePlaygroundScene', () => {
expect(document.querySelector('[data-slot="composer-frame"]')).toBeInTheDocument()
expect(document.querySelector('[data-attr="business-knowledge-playground-ask"]')).toBeInTheDocument()
})
+
+ it('lets people load older chats when another page exists', () => {
+ const loadMoreChats = jest.fn()
+ jest.mocked(useValues).mockReturnValue({ ...playgroundValues, nextChatsOffset: 1 })
+ jest.mocked(useActions).mockReturnValue({ loadMoreChats })
+ render(<BusinessKnowledgePlaygroundScene />)
+
+ fireEvent.click(screen.getByText('Load more chats'))
+ expect(
+ document.querySelector('[data-attr="business-knowledge-playground-load-more-chats"]')
+ ).toBeInTheDocument()
+ expect(loadMoreChats).toHaveBeenCalledTimes(1)
+ })
+
+ it('offers a retry when the first chat list request fails', () => {
+ const loadChats = jest.fn()
+ jest.mocked(useValues).mockReturnValue({
+ ...playgroundValues,
+ chats: [],
+ chatGroups: [],
+ chatsError: "Couldn't load chats. Try again.",
+ })
+ jest.mocked(useActions).mockReturnValue({ loadChats })
+ render(<BusinessKnowledgePlaygroundScene />)
+
+ expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load chats. Try again.")
+ expect(screen.queryByText('No chats yet')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByText('Retry'))
+ expect(loadChats).toHaveBeenCalledTimes(1)
+ })
+
+ it('shows a non-blocking retry when a populated chat list fails to refresh', () => {
+ const loadChats = jest.fn()
+ jest.mocked(useValues).mockReturnValue({
+ ...playgroundValues,
+ chatsError: "Couldn't load chats. Try again.",
+ })
+ jest.mocked(useActions).mockReturnValue({ loadChats })
+ render(<BusinessKnowledgePlaygroundScene />)
+
+ expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load chats. Try again.")
+ expect(document.querySelector('[data-attr="business-knowledge-playground-open-chat"]')).toBeInTheDocument()
+ fireEvent.click(screen.getByText('Retry'))
+ expect(loadChats).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/products/business_knowledge/frontend/scenes/playground/PlaygroundChatList.tsx b/products/business_knowledge/frontend/scenes/playground/PlaygroundChatList.tsx
index 1adc32f318a9..d480a8da7664 100644
--- a/products/business_knowledge/frontend/scenes/playground/PlaygroundChatList.tsx
+++ b/products/business_knowledge/frontend/scenes/playground/PlaygroundChatList.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconMessage, IconPlusSmall, IconSearch, IconTrash } from '@posthog/icons'
-import { LemonDialog, LemonInput, LemonSkeleton } from '@posthog/lemon-ui'
+import { LemonButton, LemonDialog, LemonInput, LemonSkeleton } from '@posthog/lemon-ui'
import { Link } from 'lib/lemon-ui/Link'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
@@ -14,10 +14,22 @@ import { businessKnowledgePlaygroundLogic } from './businessKnowledgePlaygroundL
import { formatChatAge } from './playgroundDisplay'
export function PlaygroundChatList(): JSX.Element {
- const { chats, chatsLoading, chatGroups, chatSearch, chatId, chatHasOpenTurn, deletingChatId } = useValues(
+ const {
+ chats,
+ chatsError,
+ chatsLoading,
+ chatGroups,
+ chatSearch,
+ chatId,
+ chatHasOpenTurn,
+ deletingChatId,
+ nextChatsOffset,
+ loadingMoreChats,
+ moreChatsError,
+ } = useValues(businessKnowledgePlaygroundLogic)
+ const { newChat, deleteChat, setChatSearch, loadChats, loadMoreChats } = useActions(
businessKnowledgePlaygroundLogic
)
- const { newChat, deleteChat, setChatSearch } = useActions(businessKnowledgePlaygroundLogic)
const confirmDelete = (id: string): void => {
LemonDialog.open({
@@ -39,8 +51,8 @@ export function PlaygroundChatList(): JSX.Element {
type="search"
size="small"
className="min-h-[30px] min-w-0 flex-1"
- placeholder="Filter chats"
- aria-label="Filter chats"
+ placeholder="Filter loaded chats"
+ aria-label="Filter loaded chats"
value={chatSearch}
onChange={setChatSearch}
fullWidth
@@ -65,6 +77,13 @@ export function PlaygroundChatList(): JSX.Element {
<LemonSkeleton className="h-8 opacity-60" />
<LemonSkeleton className="h-8 opacity-30" />
</div>
+ ) : chatsError && chats.length === 0 ? (
+ <div role="alert" className="flex flex-col items-center gap-2 px-2 py-8 text-center">
+ <p className="mb-0 text-xs text-danger">{chatsError}</p>
+ <LemonButton size="small" loading={chatsLoading} onClick={() => loadChats()}>
+ Retry
+ </LemonButton>
+ </div>
) : chatGroups.length === 0 ? (
<div className="m-1 rounded-md border border-dashed py-8 text-center text-muted">
<p className="mb-0 text-xs">{chatSearch ? 'No chats found' : 'No chats yet'}</p>
@@ -132,6 +151,31 @@ export function PlaygroundChatList(): JSX.Element {
</Collapsible>
))
)}
+ {chatsError && chats.length > 0 && (
+ <div role="alert" className="flex items-center gap-2 px-2 text-xs text-danger">
+ <span>{chatsError}</span>
+ <LemonButton size="small" loading={chatsLoading} onClick={() => loadChats()}>
+ Retry
+ </LemonButton>
+ </div>
+ )}
+ {moreChatsError && (
+ <p role="alert" className="px-2 text-xs text-danger">
+ {moreChatsError}
+ </p>
+ )}
+ {nextChatsOffset !== null && (
+ <LemonButton
+ size="small"
+ center
+ data-attr="business-knowledge-playground-load-more-chats"
+ loading={loadingMoreChats}
+ disabledReason={chatsLoading ? 'Wait for chats to load' : undefined}
+ onClick={() => loadMoreChats()}
+ >
+ Load more chats
+ </LemonButton>
+ )}
</div>
</aside>
)
diff --git a/products/business_knowledge/frontend/scenes/playground/businessKnowledgePlaygroundLogic.test.ts b/products/business_knowledge/frontend/scenes/playground/businessKnowledgePlaygroundLogic.test.ts
index 06eea6583ae3..4a29e464e0fc 100644
--- a/products/business_knowledge/frontend/scenes/playground/businessKnowledgePlaygroundLogic.test.ts
+++ b/products/business_knowledge/frontend/scenes/playground/businessKnowledgePlaygroundLogic.test.ts
@@ -4,6 +4,7 @@ import { expectLogic } from 'kea-test-utils'
import { ApiError } from 'lib/api'
import { urls } from 'scenes/urls'
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { initKeaTests } from '~/test/init'
import {
@@ -11,10 +12,12 @@ import {
createPlaygroundChat,
getPlaygroundChat,
listPlaygroundChats,
+ PLAYGROUND_CHAT_PAGE_SIZE,
searchKnowledge,
} from '../../api'
import type {
KnowledgeSearchResultApi,
+ PaginatedPlaygroundChatListListApi,
PlaygroundChatApi,
PlaygroundChatListApi,
SandboxRunApi,
@@ -22,6 +25,7 @@ import type {
import { businessKnowledgePlaygroundLogic } from './businessKnowledgePlaygroundLogic'
jest.mock('../../api', () => ({
+ PLAYGROUND_CHAT_PAGE_SIZE: 100,
listPlaygroundChats: jest.fn(),
createPlaygroundChat: jest.fn(),
getPlaygroundChat: jest.fn(),
@@ -88,24 +92,35 @@ const listed: PlaygroundChatListApi = {
has_open_turn: false,
}
+const listPage = (
+ results: PlaygroundChatListApi[],
+ next: string | null = null
+): PaginatedPlaygroundChatListListApi => ({
+ count: results.length,
+ next,
+ previous: null,
+ results,
+})
+
describe('businessKnowledgePlaygroundLogic', () => {
let logic: ReturnType<typeof businessKnowledgePlaygroundLogic.build>
beforeEach(() => {
initKeaTests()
jest.clearAllMocks()
- mockedList.mockResolvedValue([])
+ mockedList.mockResolvedValue(listPage([]))
logic = businessKnowledgePlaygroundLogic()
logic.mount()
})
afterEach(() => {
logic?.unmount()
+ resumeKeaLoadersErrors()
})
it('opens a saved chat from the URL', async () => {
mockedGet.mockResolvedValue(chat('completed'))
- mockedList.mockResolvedValue([listed])
+ mockedList.mockResolvedValue(listPage([listed]))
router.actions.push(urls.businessKnowledgePlayground('chat-1'))
await expectLogic(logic).toDispatchActions(['chatLoaded'])
expect(logic.values.chatId).toBe('chat-1')
@@ -304,7 +319,13 @@ describe('businessKnowledgePlaygroundLogic', () => {
])('with %i answers running elsewhere, a new chat ask is blocked: %s', async (openCount, blocked) => {
await expectLogic(logic).toDispatchActions(['loadChatsSuccess'])
mockedList.mockResolvedValue(
- Array.from({ length: openCount }, (_, index) => ({ ...listed, id: `open-${index}`, has_open_turn: true }))
+ listPage(
+ Array.from({ length: openCount }, (_, index) => ({
+ ...listed,
+ id: `open-${index}`,
+ has_open_turn: true,
+ }))
+ )
)
mockedCreate.mockResolvedValue(emptyChat)
mockedAsk.mockResolvedValue(chat('running'))
@@ -321,13 +342,121 @@ describe('businessKnowledgePlaygroundLogic', () => {
expect(logic.values.question).toBe(blocked ? 'Can I get a refund?' : '')
})
+ it('refreshes loaded history without retaining a chat deleted elsewhere', async () => {
+ await expectLogic(logic).toDispatchActions(['loadChatsSuccess'])
+ const recent = Array.from({ length: PLAYGROUND_CHAT_PAGE_SIZE }, (_, index) => ({
+ ...listed,
+ id: index === 0 ? listed.id : `chat-${index + 1}`,
+ }))
+ const deleted = { ...listed, id: 'chat-101', title: 'Deleted question' }
+ const older = { ...listed, id: 'chat-102', title: 'Older question' }
+ const replacement = { ...listed, id: 'chat-103', title: 'Next question' }
+ mockedList.mockResolvedValueOnce(listPage(recent, '/chats/?offset=100'))
+ await expectLogic(logic, () => logic.actions.loadChats()).toDispatchActions(['loadChatsSuccess'])
+
+ silenceKeaLoadersErrors()
+ mockedList.mockRejectedValueOnce(new Error('network error'))
+ logic.actions.loadMoreChats()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.nextChatsOffset).toBe(100)
+ expect(logic.values.loadingMoreChats).toBe(false)
+ expect(logic.values.moreChatsError).toContain("Couldn't load older chats")
+ resumeKeaLoadersErrors()
+
+ mockedList.mockResolvedValueOnce(listPage([deleted, older]))
+ await expectLogic(logic, () => logic.actions.loadMoreChats()).toDispatchActions(['loadMoreChatsSuccess'])
+
+ expect(mockedList).toHaveBeenLastCalledWith(100)
+ expect(logic.values.chatGroups.flatMap((group) => group.chats)).toHaveLength(102)
+ expect(logic.values.chatGroups.flatMap((group) => group.chats).at(-1)?.id).toBe('chat-102')
+ expect(logic.values.nextChatsOffset).toBeNull()
+ expect(logic.values.moreChatsError).toBeNull()
+
+ mockedList
+ .mockResolvedValueOnce(
+ listPage([{ ...listed, title: 'Updated question' }, ...recent.slice(1)], '/chats/?offset=100')
+ )
+ .mockResolvedValueOnce(listPage([older, replacement], '/chats/?offset=200'))
+ await expectLogic(logic, () => logic.actions.loadChats()).toDispatchActions(['loadChatsSuccess'])
+ expect(logic.values.chats).toHaveLength(102)
+ expect(logic.values.chats[0].title).toBe('Updated question')
+ expect(logic.values.chats.at(-1)?.title).toBe('Next question')
+ expect(logic.values.chats.some((chat) => chat.id === deleted.id)).toBe(false)
+
+ silenceKeaLoadersErrors()
+ mockedList
+ .mockResolvedValueOnce(listPage(recent, '/chats/?offset=100'))
+ .mockRejectedValueOnce(new Error('network error'))
+ logic.actions.loadChats()
+ await expectLogic(logic).toDispatchActions(['loadChatsFailure'])
+ expect(logic.values.nextChatsOffset).toBe(200)
+ expect(logic.values.chats).toHaveLength(102)
+ expect(logic.values.chatsError).toContain("Couldn't load chats")
+
+ mockedList.mockRejectedValueOnce(new Error('network error'))
+ logic.actions.loadMoreChats()
+ await expectLogic(logic).toDispatchActions(['loadMoreChatsFailure'])
+ expect(logic.values.moreChatsError).toContain("Couldn't load older chats")
+ resumeKeaLoadersErrors()
+
+ mockedList.mockResolvedValueOnce(listPage(recent))
+ await expectLogic(logic, () => logic.actions.loadChats()).toDispatchActions(['loadChatsSuccess'])
+ expect(logic.values.nextChatsOffset).toBeNull()
+ expect(logic.values.moreChatsError).toBeNull()
+ })
+
+ it.each(['refresh first', 'load more first'])('keeps the refreshed list when %s resolves', async (order) => {
+ await expectLogic(logic).toDispatchActions(['loadChatsSuccess'])
+ const recent = Array.from({ length: PLAYGROUND_CHAT_PAGE_SIZE }, (_, index) => ({
+ ...listed,
+ id: `chat-${index}`,
+ }))
+ mockedList.mockResolvedValueOnce(listPage(recent, '/chats/?offset=100'))
+ await expectLogic(logic, () => logic.actions.loadChats()).toDispatchActions(['loadChatsSuccess'])
+
+ let resolveMore: (page: PaginatedPlaygroundChatListListApi) => void = () => {}
+ let resolveRefresh: (page: PaginatedPlaygroundChatListListApi) => void = () => {}
+ mockedList.mockReturnValueOnce(new Promise((resolve) => (resolveMore = resolve)))
+ logic.actions.loadMoreChats()
+ mockedList.mockReturnValueOnce(new Promise((resolve) => (resolveRefresh = resolve)))
+ logic.actions.loadChats()
+
+ if (order === 'load more first') {
+ resolveMore(listPage([{ ...listed, id: 'stale-chat' }]))
+ await Promise.resolve()
+ }
+ resolveRefresh(listPage(recent.slice(0, 1)))
+ await Promise.resolve()
+ if (order === 'refresh first') {
+ resolveMore(listPage([{ ...listed, id: 'stale-chat' }]))
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.chats.map((chat) => chat.id)).toEqual([recent[0].id])
+ expect(logic.values.nextChatsOffset).toBeNull()
+ })
+
+ it('shows a first-page failure and clears it when the retry starts', async () => {
+ await expectLogic(logic).toDispatchActions(['loadChatsSuccess'])
+ silenceKeaLoadersErrors()
+ mockedList.mockRejectedValueOnce(new Error('network error'))
+ logic.actions.loadChats()
+ await expectLogic(logic).toDispatchActions(['loadChatsFailure'])
+ expect(logic.values.chatsError).toContain("Couldn't load chats")
+ expect(logic.values.chats).toEqual([])
+
+ mockedList.mockResolvedValueOnce(listPage([listed]))
+ await expectLogic(logic, () => logic.actions.loadChats()).toDispatchActions(['loadChatsSuccess'])
+ expect(logic.values.chatsError).toBeNull()
+ expect(logic.values.chats).toEqual([listed])
+ })
+
it('refreshes the chat list until no chat has an answer running', async () => {
await expectLogic(logic).toDispatchActions(['loadChatsSuccess'])
jest.useFakeTimers()
try {
mockedList
- .mockResolvedValueOnce([{ ...listed, has_open_turn: true }])
- .mockResolvedValue([{ ...listed, has_open_turn: false }])
+ .mockResolvedValueOnce(listPage([{ ...listed, has_open_turn: true }]))
+ .mockResolvedValue(listPage([{ ...listed, has_open_turn: false }]))
await expectLogic(logic, () => {
logic.actions.loadChats()
}).toDispatchActions(['loadChatsSuccess'])
diff --git a/products/business_knowledge/frontend/scenes/playground/businessKnowledgePlaygroundLogic.ts b/products/business_knowledge/frontend/scenes/playground/businessKnowledgePlaygroundLogic.ts
index 09bdefaade24..a4892ddf3c7d 100644
--- a/products/business_knowledge/frontend/scenes/playground/businessKnowledgePlaygroundLogic.ts
+++ b/products/business_knowledge/frontend/scenes/playground/businessKnowledgePlaygroundLogic.ts
@@ -12,6 +12,7 @@ import {
deletePlaygroundChat,
getPlaygroundChat,
listPlaygroundChats,
+ PLAYGROUND_CHAT_PAGE_SIZE,
searchKnowledge,
} from '../../api'
import type {
@@ -51,9 +52,13 @@ export interface businessKnowledgePlaygroundLogicValues {
chatLoading: boolean
chatSearch: string
chats: PlaygroundChatListApi[]
+ chatsError: string | null
chatsLoading: boolean
deletingChatId: string | null
+ loadingMoreChats: boolean
mode: PlaygroundMode
+ moreChatsError: string | null
+ nextChatsOffset: number | null
pendingQuestion: string | null
question: string
searchError: string | null
@@ -73,7 +78,7 @@ export interface businessKnowledgePlaygroundLogicActions {
deleteChat: (chatId: string) => {
chatId: string
}
- loadChats: () => any
+ loadChats: (_: void) => void
loadChatsFailure: (
error: string,
errorObject?: any
@@ -83,10 +88,25 @@ export interface businessKnowledgePlaygroundLogicActions {
}
loadChatsSuccess: (
chats: PlaygroundChatListApi[],
- payload?: any
+ payload?: void
) => {
chats: PlaygroundChatListApi[]
- payload?: any
+ payload?: void
+ }
+ loadMoreChats: (_: void) => void
+ loadMoreChatsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMoreChatsSuccess: (
+ chats: PlaygroundChatListApi[],
+ payload?: void
+ ) => {
+ chats: PlaygroundChatListApi[]
+ payload?: void
}
newChat: () => {
value: true
@@ -127,6 +147,9 @@ export interface businessKnowledgePlaygroundLogicActions {
setMode: (mode: PlaygroundMode) => {
mode: PlaygroundMode
}
+ setNextChatsOffset: (offset: number | null) => {
+ offset: number | null
+ }
setPendingQuestion: (pendingQuestion: string | null) => {
pendingQuestion: string | null
}
@@ -184,6 +207,7 @@ export const businessKnowledgePlaygroundLogic = kea<businessKnowledgePlaygroundL
setChatId: (chatId: string | null) => ({ chatId }),
openChat: (chatId: string | null) => ({ chatId }),
newChat: true,
+ setNextChatsOffset: (offset: number | null) => ({ offset }),
deleteChat: (chatId: string) => ({ chatId }),
setDeletingChatId: (deletingChatId: string | null) => ({ deletingChatId }),
ask: true,
@@ -198,15 +222,80 @@ export const businessKnowledgePlaygroundLogic = kea<businessKnowledgePlaygroundL
setSearchResults: (searchResults: KnowledgeSearchResultApi[]) => ({ searchResults }),
setSearchError: (searchError: string | null) => ({ searchError }),
}),
- loaders(() => ({
+ loaders(({ actions, values, cache }) => ({
chats: [
[] as PlaygroundChatListApi[],
{
- loadChats: async (): Promise<PlaygroundChatListApi[]> => listPlaygroundChats(),
+ loadChats: async (_: void, breakpoint): Promise<PlaygroundChatListApi[]> => {
+ cache.chatsGeneration = (cache.chatsGeneration ?? 0) + 1
+ const generation = cache.chatsGeneration
+ cache.refreshingChats = true
+ const loadedCount = Math.max(values.chats.length, PLAYGROUND_CHAT_PAGE_SIZE)
+ const chats: PlaygroundChatListApi[] = []
+ let offset = 0
+ let page
+ try {
+ do {
+ page = await listPlaygroundChats(offset)
+ breakpoint()
+ chats.push(...page.results)
+ offset += PLAYGROUND_CHAT_PAGE_SIZE
+ } while (page.next && offset < loadedCount)
+ actions.setNextChatsOffset(page.next ? offset : null)
+ const uniqueChats = new Map<string, PlaygroundChatListApi>()
+ for (const chat of chats) {
+ if (!uniqueChats.has(chat.id)) {
+ uniqueChats.set(chat.id, chat)
+ }
+ }
+ return [...uniqueChats.values()]
+ } finally {
+ if (cache.chatsGeneration === generation) {
+ cache.refreshingChats = false
+ }
+ }
+ },
+ loadMoreChats: async (_: void, breakpoint): Promise<PlaygroundChatListApi[]> => {
+ const offset = values.nextChatsOffset
+ if (offset === null || cache.refreshingChats) {
+ return values.chats
+ }
+ const generation = cache.chatsGeneration
+ const page = await listPlaygroundChats(offset)
+ breakpoint()
+ if (cache.chatsGeneration !== generation || values.nextChatsOffset !== offset) {
+ return values.chats
+ }
+ actions.setNextChatsOffset(page.next ? offset + PLAYGROUND_CHAT_PAGE_SIZE : null)
+ const loadedIds = new Set(values.chats.map((chat) => chat.id))
+ return [...values.chats, ...page.results.filter((chat) => !loadedIds.has(chat.id))]
+ },
},
],
})),
reducers({
+ chatsError: [
+ null as string | null,
+ {
+ loadChats: () => null,
+ loadChatsFailure: (_, { error, errorObject }) =>
+ errorDetail(errorObject ?? error, "Couldn't load chats. Try again."),
+ },
+ ],
+ nextChatsOffset: [null as number | null, { setNextChatsOffset: (_, { offset }) => offset }],
+ loadingMoreChats: [
+ false,
+ { loadMoreChats: () => true, loadMoreChatsSuccess: () => false, loadMoreChatsFailure: () => false },
+ ],
+ moreChatsError: [
+ null as string | null,
+ {
+ loadMoreChats: () => null,
+ loadChatsSuccess: () => null,
+ loadMoreChatsFailure: (_, { error, errorObject }) =>
+ errorDetail(errorObject ?? error, "Couldn't load older chats. Try again."),
+ },
+ ],
question: [
'',
{
@@ -322,7 +411,9 @@ export const businessKnowledgePlaygroundLogic = kea<businessKnowledgePlaygroundL
if (chatHasOpenTurn) {
return 'Wait for this answer to finish.'
}
- const openElsewhere = chats.filter((listed) => listed.id !== chatId && listed.has_open_turn).length
+ const openElsewhere = chats
+ .slice(0, PLAYGROUND_CHAT_PAGE_SIZE)
+ .filter((listed) => listed.id !== chatId && listed.has_open_turn).length
return openElsewhere >= MAX_OPEN_ANSWERS
? `You have ${MAX_OPEN_ANSWERS} answers running. Wait for one to finish before you ask another question.`
: null
@@ -352,7 +443,7 @@ export const businessKnowledgePlaygroundLogic = kea<businessKnowledgePlaygroundL
return {
loadChatsSuccess: ({ chats }) => {
// Other chats keep running in the background, so refresh the list until their spinners can clear.
- if (chats.some((chat) => chat.has_open_turn)) {
+ if (chats.slice(0, PLAYGROUND_CHAT_PAGE_SIZE).some((chat) => chat.has_open_turn)) {
cache.disposables.add(() => {
const id = window.setTimeout(() => actions.loadChats(), LIST_POLL_MS)
return () => window.clearTimeout(id)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 97da62bd6db8..2202f411c078 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -73071,6 +73071,28 @@ export namespace Schemas {
results: PlatformAlertConfiguration[];
}
+ export interface PlaygroundChatList {
+ /** Playground chat id. */
+ id: string;
+ /** First question, truncated. Empty until someone asks. */
+ title: string;
+ /** When this chat was created. */
+ created_at: string;
+ /** When this chat was last asked in. */
+ updated_at: string;
+ /** True while an answer in this chat is still running. Another question in this chat returns 409 until it finishes. */
+ has_open_turn: boolean;
+ }
+
+ export interface PaginatedPlaygroundChatListList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: PlaygroundChatList[];
+ }
+
/**
* * `SYSTEM` - SYSTEM
* * `PLUGIN` - PLUGIN
@@ -91796,19 +91818,6 @@ export namespace Schemas {
turns: PlaygroundTurn[];
}
- export interface PlaygroundChatList {
- /** Playground chat id. */
- id: string;
- /** First question, truncated. Empty until someone asks. */
- title: string;
- /** When this chat was created. */
- created_at: string;
- /** When this chat was last asked in. */
- updated_at: string;
- /** True while an answer in this chat is still running. Another question in this chat returns 409 until it finishes. */
- has_open_turn: boolean;
- }
-
/**
* Query parameters to send to the target.
*/
@@ -124116,6 +124125,17 @@ export namespace Schemas {
ticket_id?: string;
};
+ export type BusinessKnowledgePlaygroundChatsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type BusinessKnowledgeRepositoriesFileRetrieveParams = {
/**
* Require the repository to be in this library. Pass the same id used for document search and repository search. Omit to read any selected repository.