Skip to content

Automate browser based workflows with AI

SKY-11307 Add Copilot chat history scoped to the workflow (frontend) (#6767)

Celal Zamanoğlubdf3ce55120c
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index b28bc0bbb..1dc1940c9 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -41,10 +41,12 @@ import {
WorkflowCopilotWorkflowDraftUpdate,
WorkflowCopilotChatSender,
WorkflowCopilotChatRequest,
+ WorkflowCopilotChatSummary,
WorkflowCopilotClearProposedWorkflowRequest,
WorkflowCopilotApplyProposedWorkflowRequest,
WorkflowCopilotAudioUploadResponse,
} from "./workflowCopilotTypes";
+import { WorkflowCopilotHistory } from "./WorkflowCopilotHistory";
import { shouldWaitForLiveBrowser } from "./browserReadiness";
import {
QueuedPromptReason,
@@ -666,6 +668,91 @@ export function WorkflowCopilotChat({
repin();
};
+ const applyHistoryResponse = useCallback(
+ (data: WorkflowCopilotChatHistoryResponse) => {
+ const historyMessages = data.chat_history.map((message, index) => ({
+ id: `${index}-${Date.now()}`,
+ sender: message.sender,
+ content: message.content,
+ timestamp: message.created_at,
+ narrative: (() => {
+ const hydrated = hydrateHistoryNarrative(
+ message.narrative_payload,
+ message.turn_outcome,
+ );
+ if (!hydrated) return undefined;
+ // Fall back to the legacy message body when the persisted payload
+ // predates terminal-text capture.
+ if (!hydrated.terminalMessage && message.content) {
+ return {
+ ...hydrated,
+ terminalMessage: message.content,
+ narrativeSummary: hydrated.narrativeSummary ?? message.content,
+ };
+ }
+ return hydrated;
+ })(),
+ }));
+ setMessages(historyMessages);
+ setWorkflowCopilotChatId(data.workflow_copilot_chat_id);
+ setProposedWorkflow(data.proposed_workflow ?? null);
+ setAutoAccept(data.auto_accept ?? false);
+ },
+ // Only stable state setters are referenced, so the callback never needs to change.
+ [],
+ );
+
+ const loadChatInPlace = useCallback(
+ async (chatId: string) => {
+ if (!workflowPermanentId) return;
+ setIsLoadingHistory(true);
+ updateQueuedPrompt(null);
+ setNarrative(EMPTY_NARRATIVE);
+ turnSnapshots.current.clear();
+ pendingSubmitSnapshot.current = null;
+ latestTurnId.current = null;
+ repin();
+ try {
+ const client = await getClient(credentialGetter, "sans-api-v1");
+ const response = await client.get<WorkflowCopilotChatHistoryResponse>(
+ "/workflow/copilot/chat-history",
+ {
+ params: {
+ workflow_permanent_id: workflowPermanentId,
+ workflow_copilot_chat_id: chatId,
+ },
+ },
+ );
+ applyHistoryResponse(response.data);
+ // Mark history loaded for this workflow so the mount effect won't reload
+ // the latest chat over the one the user just selected.
+ historyLoadedForRef.current = workflowPermanentId;
+ } catch (error) {
+ console.error("Failed to load chat:", error);
+ toast({ title: "Failed to load chat", variant: "destructive" });
+ } finally {
+ setIsLoadingHistory(false);
+ }
+ },
+ [
+ credentialGetter,
+ workflowPermanentId,
+ applyHistoryResponse,
+ updateQueuedPrompt,
+ repin,
+ ],
+ );
+
+ const handleSelectHistoryChat = useCallback(
+ (chat: WorkflowCopilotChatSummary) => {
+ if (chat.workflow_copilot_chat_id === workflowCopilotChatIdRef.current) {
+ return;
+ }
+ void loadChatInPlace(chat.workflow_copilot_chat_id);
+ },
+ [loadChatInPlace],
+ );
+
const applyWorkflowUpdate = useCallback(
(
workflow: WorkflowApiResponse,
@@ -923,36 +1010,7 @@ export function WorkflowCopilotChat({
if (!isMounted) return;
- const historyMessages = response.data.chat_history.map(
- (message, index) => ({
- id: `${index}-${Date.now()}`,
- sender: message.sender,
- content: message.content,
- timestamp: message.created_at,
- narrative: (() => {
- const hydrated = hydrateHistoryNarrative(
- message.narrative_payload,
- message.turn_outcome,
- );
- if (!hydrated) return undefined;
- // Fall back to the legacy message body when the persisted
- // payload predates terminal-text capture.
- if (!hydrated.terminalMessage && message.content) {
- return {
- ...hydrated,
- terminalMessage: message.content,
- narrativeSummary:
- hydrated.narrativeSummary ?? message.content,
- };
- }
- return hydrated;
- })(),
- }),
- );
- setMessages(historyMessages);
- setWorkflowCopilotChatId(response.data.workflow_copilot_chat_id);
- setProposedWorkflow(response.data.proposed_workflow ?? null);
- setAutoAccept(response.data.auto_accept ?? false);
+ applyHistoryResponse(response.data);
historyLoadedForRef.current = workflowPermanentId;
} catch (error) {
console.error("Failed to load chat history:", error);
@@ -968,7 +1026,13 @@ export function WorkflowCopilotChat({
return () => {
isMounted = false;
};
- }, [credentialGetter, repin, updateQueuedPrompt, workflowPermanentId]);
+ }, [
+ credentialGetter,
+ repin,
+ updateQueuedPrompt,
+ workflowPermanentId,
+ applyHistoryResponse,
+ ]);
const cancelSend = useCallback(async () => {
// Capture upfront so the 15s timer below can't latch onto a next turn's controller.
@@ -1925,6 +1989,12 @@ export function WorkflowCopilotChat({
Agent Copilot (Beta)
</h3>
<div className="flex items-center gap-2">
+ <WorkflowCopilotHistory
+ workflowPermanentId={workflowPermanentId}
+ currentChatId={workflowCopilotChatId}
+ onSelect={handleSelectHistoryChat}
+ disabled={isLoading || isLoadingHistory}
+ />
<button
type="button"
onClick={handleNewChat}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.test.tsx
new file mode 100644
index 000000000..f2520a15e
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.test.tsx
@@ -0,0 +1,127 @@
+// @vitest-environment jsdom
+
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { WorkflowCopilotHistory } from "./WorkflowCopilotHistory";
+import { WorkflowCopilotChatSummary } from "./workflowCopilotTypes";
+
+const { mockHook } = vi.hoisted(() => ({ mockHook: vi.fn() }));
+
+vi.mock("./useInfiniteCopilotChatsQuery", () => ({
+ useInfiniteCopilotChatsQuery: mockHook,
+}));
+
+const chats: WorkflowCopilotChatSummary[] = [
+ {
+ workflow_copilot_chat_id: "wcc_1",
+ workflow_permanent_id: "wpid_a",
+ workflow_title: "Login flow",
+ title: "Build a login flow",
+ created_at: "2026-06-20T10:00:00Z",
+ modified_at: "2026-06-20T10:05:00Z",
+ },
+ {
+ workflow_copilot_chat_id: "wcc_2",
+ workflow_permanent_id: "wpid_b",
+ workflow_title: "Scraper",
+ title: "Scrape the news",
+ created_at: "2026-06-21T10:00:00Z",
+ modified_at: "2026-06-21T10:05:00Z",
+ },
+];
+
+function mockChats(pages: WorkflowCopilotChatSummary[][]) {
+ mockHook.mockReturnValue({
+ data: { pages },
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ isFetching: false,
+ });
+}
+
+afterEach(cleanup);
+beforeEach(() => mockHook.mockReset());
+
+describe("WorkflowCopilotHistory", () => {
+ it("renders the workflow's chats when opened", async () => {
+ mockChats([chats]);
+ render(
+ <WorkflowCopilotHistory
+ workflowPermanentId="wpid_a"
+ currentChatId={null}
+ onSelect={vi.fn()}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /history/i }));
+
+ expect(await screen.findByText("Build a login flow")).toBeTruthy();
+ expect(screen.getByText("Scrape the news")).toBeTruthy();
+ });
+
+ it("calls onSelect with the chosen chat", async () => {
+ mockChats([chats]);
+ const onSelect = vi.fn();
+ render(
+ <WorkflowCopilotHistory
+ workflowPermanentId="wpid_a"
+ currentChatId={null}
+ onSelect={onSelect}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /history/i }));
+ fireEvent.click(await screen.findByText("Scrape the news"));
+
+ expect(onSelect).toHaveBeenCalledWith(chats[1]);
+ });
+
+ it("shows an empty state when there are no chats", async () => {
+ mockChats([[]]);
+ render(
+ <WorkflowCopilotHistory
+ workflowPermanentId="wpid_a"
+ currentChatId={null}
+ onSelect={vi.fn()}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /history/i }));
+
+ expect(await screen.findByText("No chats found")).toBeTruthy();
+ });
+
+ it("feeds the workflow id and debounced search into the query", async () => {
+ mockChats([chats]);
+ render(
+ <WorkflowCopilotHistory
+ workflowPermanentId="wpid_a"
+ currentChatId={null}
+ onSelect={vi.fn()}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /history/i }));
+ const input = await screen.findByPlaceholderText("Search chats...");
+ fireEvent.change(input, { target: { value: "deploy" } });
+
+ await waitFor(
+ () =>
+ expect(mockHook).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workflow_permanent_id: "wpid_a",
+ search: "deploy",
+ }),
+ ),
+ { timeout: 1500 },
+ );
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.tsx
new file mode 100644
index 000000000..1b873249b
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.tsx
@@ -0,0 +1,185 @@
+import { useEffect, useMemo, useState } from "react";
+import {
+ CheckIcon,
+ CounterClockwiseClockIcon,
+ MagnifyingGlassIcon,
+ ReloadIcon,
+} from "@radix-ui/react-icons";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Skeleton } from "@/components/ui/skeleton";
+import { handleInfiniteScroll } from "@/util/utils";
+import { compactLocalDateTime } from "@/util/timeFormat";
+import { useDebounce } from "use-debounce";
+import { useInfiniteCopilotChatsQuery } from "./useInfiniteCopilotChatsQuery";
+import { WorkflowCopilotChatSummary } from "./workflowCopilotTypes";
+
+interface WorkflowCopilotHistoryProps {
+ workflowPermanentId: string | undefined;
+ currentChatId: string | null;
+ onSelect: (chat: WorkflowCopilotChatSummary) => void;
+ disabled?: boolean;
+}
+
+interface WorkflowCopilotHistoryContentProps {
+ workflowPermanentId: string | undefined;
+ currentChatId: string | null;
+ onSelect: (chat: WorkflowCopilotChatSummary) => void;
+}
+
+// Lives inside PopoverContent so the react-query subscription only mounts while
+// the dropdown is open.
+function WorkflowCopilotHistoryContent({
+ workflowPermanentId,
+ currentChatId,
+ onSelect,
+}: WorkflowCopilotHistoryContentProps) {
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search, 500);
+ const isTyping = search !== debouncedSearch;
+
+ const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isFetching } =
+ useInfiniteCopilotChatsQuery({
+ workflow_permanent_id: workflowPermanentId,
+ search: debouncedSearch,
+ page_size: 20,
+ });
+
+ const chats = useMemo(
+ () => data?.pages.flatMap((page) => page) ?? [],
+ [data],
+ );
+
+ return (
+ <>
+ <div className="border-b p-3">
+ <h4 className="mb-2 text-sm font-medium">Chat history</h4>
+ <div className="relative">
+ <MagnifyingGlassIcon className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
+ <Input
+ placeholder="Search chats..."
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ className="h-8 pl-8"
+ autoFocus
+ />
+ </div>
+ </div>
+ <div
+ className="max-h-[300px] overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:border-2 [&::-webkit-scrollbar-thumb]:border-slate-100 [&::-webkit-scrollbar-thumb]:bg-slate-300 dark:[&::-webkit-scrollbar-thumb]:border-slate-800 dark:[&::-webkit-scrollbar-thumb]:bg-slate-600 [&::-webkit-scrollbar-track]:bg-slate-100 dark:[&::-webkit-scrollbar-track]:bg-slate-800 [&::-webkit-scrollbar]:w-2"
+ onScroll={(e) =>
+ handleInfiniteScroll(
+ e,
+ fetchNextPage,
+ hasNextPage,
+ isFetchingNextPage,
+ )
+ }
+ >
+ {(isFetching || isTyping) && chats.length === 0 ? (
+ <>
+ {Array.from({ length: 8 }).map((_, index) => (
+ <div
+ key={`skeleton-${index}`}
+ className="flex w-full flex-col gap-1 px-3 py-2"
+ >
+ <Skeleton className="h-4 w-3/4" />
+ <Skeleton className="h-3 w-1/2" />
+ </div>
+ ))}
+ </>
+ ) : chats.length === 0 ? (
+ <div className="px-3 py-8 text-center text-sm text-slate-400">
+ No chats found
+ </div>
+ ) : (
+ <>
+ {chats.map((chat) => {
+ const isCurrent = currentChatId === chat.workflow_copilot_chat_id;
+ return (
+ <button
+ key={chat.workflow_copilot_chat_id}
+ type="button"
+ onClick={() => onSelect(chat)}
+ className="flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm transition-colors hover:bg-slate-50 dark:hover:bg-slate-800"
+ >
+ <div className="flex min-w-0 flex-col">
+ <span className="line-clamp-2 break-words [overflow-wrap:anywhere]">
+ {chat.title || "Untitled chat"}
+ </span>
+ <span className="truncate text-xs text-slate-400">
+ {compactLocalDateTime(chat.created_at)}
+ </span>
+ </div>
+ {isCurrent && (
+ <CheckIcon className="h-4 w-4 shrink-0 text-blue-400" />
+ )}
+ </button>
+ );
+ })}
+ {isFetchingNextPage && (
+ <div className="flex items-center justify-center py-2">
+ <ReloadIcon className="h-3 w-3 animate-spin text-slate-400" />
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </>
+ );
+}
+
+function WorkflowCopilotHistory({
+ workflowPermanentId,
+ currentChatId,
+ onSelect,
+ disabled = false,
+}: WorkflowCopilotHistoryProps) {
+ const [open, setOpen] = useState(false);
+
+ // Close the dropdown when the copilot starts loading so a selection can't
+ // race an in-flight turn or chat load.
+ useEffect(() => {
+ if (disabled) {
+ setOpen(false);
+ }
+ }, [disabled]);
+
+ function handleSelect(chat: WorkflowCopilotChatSummary) {
+ setOpen(false);
+ onSelect(chat);
+ }
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ disabled={disabled}
+ onMouseDown={(e) => e.stopPropagation()}
+ className="flex items-center gap-1 rounded border border-border px-2 py-1 text-xs text-muted-foreground hover:bg-accent hover:text-accent-foreground disabled:opacity-50"
+ >
+ <CounterClockwiseClockIcon className="h-3 w-3" aria-hidden="true" />
+ History
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ className="w-80 p-0"
+ align="end"
+ onCloseAutoFocus={(e) => e.preventDefault()}
+ >
+ <WorkflowCopilotHistoryContent
+ workflowPermanentId={workflowPermanentId}
+ currentChatId={currentChatId}
+ onSelect={handleSelect}
+ />
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+export { WorkflowCopilotHistory };
diff --git a/skyvern-frontend/src/routes/workflows/copilot/useInfiniteCopilotChatsQuery.ts b/skyvern-frontend/src/routes/workflows/copilot/useInfiniteCopilotChatsQuery.ts
new file mode 100644
index 000000000..24646df54
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/useInfiniteCopilotChatsQuery.ts
@@ -0,0 +1,56 @@
+import { useInfiniteQuery } from "@tanstack/react-query";
+import { getClient } from "@/api/AxiosClient";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { WorkflowCopilotChatSummary } from "./workflowCopilotTypes";
+
+interface UseInfiniteCopilotChatsQueryParams {
+ workflow_permanent_id?: string;
+ search?: string;
+ page_size?: number;
+ enabled?: boolean;
+}
+
+function useInfiniteCopilotChatsQuery({
+ workflow_permanent_id,
+ search,
+ page_size = 20,
+ enabled = true,
+}: UseInfiniteCopilotChatsQueryParams = {}) {
+ const credentialGetter = useCredentialGetter();
+
+ return useInfiniteQuery({
+ queryKey: [
+ "copilot-chats",
+ "infinite",
+ { workflow_permanent_id, search, page_size },
+ ],
+ queryFn: async ({ pageParam = 1 }) => {
+ const client = await getClient(credentialGetter, "sans-api-v1");
+ const searchParams = new URLSearchParams();
+ searchParams.append("page", String(pageParam));
+ searchParams.append("page_size", String(page_size));
+ if (workflow_permanent_id) {
+ searchParams.append("workflow_permanent_id", workflow_permanent_id);
+ }
+ if (search) {
+ searchParams.append("search", search);
+ }
+ return client
+ .get<Array<WorkflowCopilotChatSummary>>("/workflow/copilot/chats", {
+ params: searchParams,
+ })
+ .then((response) => response.data);
+ },
+ getNextPageParam: (lastPage, allPages) => {
+ // A full page implies a possible next one; an exact-multiple total costs one empty fetch.
+ if (lastPage.length === page_size) {
+ return allPages.length + 1;
+ }
+ return undefined;
+ },
+ initialPageParam: 1,
+ enabled,
+ });
+}
+
+export { useInfiniteCopilotChatsQuery };
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index 3523cd0ad..db0285b0a 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -67,6 +67,16 @@ export interface WorkflowCopilotChatHistoryResponse {
auto_accept?: boolean | null;
}
+export interface WorkflowCopilotChatSummary {
+ workflow_copilot_chat_id: string;
+ workflow_permanent_id: string;
+ // Returned by the API; not rendered since the list is already scoped to one workflow.
+ workflow_title?: string | null;
+ title: string;
+ created_at: string;
+ modified_at: string;
+}
+
export interface WorkflowCopilotClearProposedWorkflowRequest {
workflow_copilot_chat_id: string;
auto_accept: boolean;