Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Show a searchable org-credential picker for copilot credential asks (SKY-12832) (#8026)
Celal Zamanoğlu1ee85ab4f6f4
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsxindex e4ec76662..df3e9608f 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx@@ -115,37 +115,77 @@ vi.mock("@/hooks/useCredentialGetter", () => ({vi.mock("@/components/ui/use-toast", () => ({ toast: toastFn }));-const { selectValueChange } = vi.hoisted(() => ({- selectValueChange: { current: null as ((value: string) => void) | null },-}));--vi.mock("@/components/ui/select", () => ({- Select: ({- children,- onValueChange,- }: {- children?: ReactNode;- onValueChange?: (value: string) => void;- }) => {- selectValueChange.current = onValueChange ?? null;- return <div data-testid="mock-select">{children}</div>;- },- SelectTrigger: ({ children }: { children?: ReactNode }) => (- <div>{children}</div>+// Radix Popover + cmdk misbehave in jsdom; stub them so the picker's items are clickable buttons.+// Unlike the card unit test's always-render stub, this one honors `open` and wires the trigger —+// WorkflowCopilotHistory also renders a Popover whose (closed) content pulls react-query, so an+// unconditional PopoverContent would force-mount it and crash with "No QueryClient".+vi.mock("@/components/ui/popover", async () => {+ const React = await import("react");+ const OpenCtx = React.createContext<{+ open: boolean;+ setOpen: (value: boolean) => void;+ }>({ open: false, setOpen: () => {} });+ return {+ Popover: ({+ open,+ onOpenChange,+ children,+ }: {+ open?: boolean;+ onOpenChange?: (value: boolean) => void;+ children?: ReactNode;+ }) => (+ <OpenCtx.Provider+ value={{ open: Boolean(open), setOpen: onOpenChange ?? (() => {}) }}+ >+ {children}+ </OpenCtx.Provider>+ ),+ PopoverTrigger: ({ children }: { children?: ReactNode }) => {+ const { open, setOpen } = React.useContext(OpenCtx);+ return <div onClick={() => setOpen(!open)}>{children}</div>;+ },+ PopoverContent: ({ children }: { children?: ReactNode }) => {+ const { open } = React.useContext(OpenCtx);+ return open ? <div>{children}</div> : null;+ },+ };+});+vi.mock("@/components/ui/command", () => ({+ Command: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ CommandInput: ({ placeholder }: { placeholder?: string }) => (+ <input placeholder={placeholder} />),- SelectValue: ({ placeholder }: { placeholder?: string }) => (- <span>{placeholder}</span>+ CommandList: ({ children }: { children?: ReactNode }) => (+ <div>{children}</div>),- SelectContent: ({ children }: { children?: ReactNode }) => (+ CommandEmpty: ({ children }: { children?: ReactNode }) => (<div>{children}</div>),- SelectItem: ({+ CommandGroup: ({children,- value,+ heading,}: {children?: ReactNode;- value: string;- }) => <div data-testid={`select-item-${value}`}>{children}</div>,+ heading?: string;+ }) => (+ <div>+ {heading ? <div>{heading}</div> : null}+ {children}+ </div>+ ),+ CommandItem: ({+ children,+ onSelect,+ }: {+ children?: ReactNode;+ onSelect?: () => void;+ value?: string;+ }) => (+ <button type="button" onClick={() => onSelect?.()}>+ {children}+ </button>+ ),}));// The real modal pulls react-query; a stub is enough to prove the connect →@@ -332,6 +372,30 @@ const errorFrame = (turnId = "turn-1") => ({turn_id: turnId,});+// A continuation the user cancels: a terminal response flagged cancelled, which+// flows through handleResponse (not the error path).+const cancelledContinuationResponse = (turnId = "turn-10") => ({+ type: "response",+ workflow_copilot_chat_id: "chat-1",+ message: "Canceled.",+ updated_workflow: null,+ cancelled: true,+ response_time: "2026-07-13T00:00:05Z",+ proposal_disposition: "no_proposal",+ turn_id: turnId,+ narrative_payload: {+ turnId,+ turnIndex: 1,+ mode: "build",+ responseType: "REPLY",+ terminal: "response",+ terminalMessage: "Canceled.",+ narrativeSummary: "Canceled.",+ startedAt: "2026-07-13T00:00:00Z",+ endedAt: "2026-07-13T00:00:05Z",+ },+});+function credentialResponsePosts() {return sansApiPost.mock.calls.filter((call) => call[0] === "/workflow/copilot/credential-response",@@ -433,9 +497,10 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {streamCalls[0]!.onMessage(turnStart());streamCalls[0]!.onMessage(credentialFrame());});- const useButton = await screen.findByRole("button", {- name: /Use 'HN Login'/,+ await act(async () => {+ fireEvent.click(await screen.findByRole("combobox"));});+ const useButton = await screen.findByRole("button", { name: "HN Login" });await act(async () => {fireEvent.click(useButton);});@@ -500,7 +565,7 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {expect(postStreaming).toHaveBeenCalledTimes(1);});- it("offers the credential_refs candidates even when none has a tested_url", async () => {+ it("shows the full org credential list on a pause ask (not just the frame's candidates) and answers via the typed POST", async () => {flagMap.current = { [COPILOT_UX_V1_FLAG]: true };credentialsData.current = [{ credential_id: "cred-abc", name: "abc", tested_url: null },@@ -516,13 +581,20 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {credentialFrame({ credential_refs: ["cred-abc", "cred-spare"] }),);});- expect(await screen.findByText("Use existing…")).toBeTruthy();- expect(screen.getByTestId("select-item-cred-abc")).toBeTruthy();- expect(screen.getByTestId("select-item-cred-spare")).toBeTruthy();- expect(screen.queryByTestId("select-item-cred-other")).toBeNull();await act(async () => {- selectValueChange.current?.("cred-spare");+ fireEvent.click(await screen.findByRole("combobox"));+ });+ // The copilot suggestion (credential_refs) is pinned under "Suggested"; the full org list —+ // including the credential NOT in credential_refs — stays below to override.+ expect(await screen.findByText("Suggested")).toBeTruthy();+ expect(screen.getByText("All credentials")).toBeTruthy();+ expect(screen.getByRole("button", { name: "abc" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "spare-portal" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "unrelated" })).toBeTruthy();+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "spare-portal" }));});+ // The pick answers through the typed resume POST (which origin-binds), not a chat message.await waitFor(() => expect(credentialResponsePosts()).toHaveLength(1));expect(credentialResponsePosts()[0]![1]).toMatchObject({action: "connected",@@ -564,7 +636,7 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {errSpy.mockRestore();});- it("retries the credentials fetch on a later pause after a transient failure (no poisoned cache)", async () => {+ it("degrades a pause ask to the Connect-credential CTA when the credentials fetch fails", async () => {flagMap.current = { [COPILOT_UX_V1_FLAG]: true };const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});credsFail.current = true;@@ -578,16 +650,12 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {await waitFor(() =>expect(credentialsGets().length).toBeGreaterThanOrEqual(1),);- const afterFailure = credentialsGets().length;- // A later pause frame must trigger a fresh fetch — caching [] on failure- // would have left credentialsList non-null and blocked all retries.- credsFail.current = false;- await act(async () => {- streamCalls[0]!.onMessage(credentialFrame({ turn_id: "turn-b" }));- });- await waitFor(() =>- expect(credentialsGets().length).toBeGreaterThan(afterFailure),- );+ // Failed fetch → no picker (null, not a cached []); the Connect-credential CTA remains so the+ // user can still create one, and the pause stays answerable.+ expect(+ await screen.findByRole("button", { name: "Connect credential" }),+ ).toBeTruthy();+ expect(screen.queryByText("Use existing…")).toBeNull();errSpy.mockRestore();});@@ -667,11 +735,10 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {await act(async () => {fireEvent.click(createBtn);});- // A fresh turn is sent (exactly one) referencing the connected credential.+ // A fresh turn is sent (exactly one) referencing the connected credential by id (the+ // deterministic _explicit_credential_ids path), not by name.await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));- expect(streamCalls[1]!.body.message).toContain(- "I've connected the credential 'New Login'",- );+ expect(streamCalls[1]!.body.message).toContain("new-cred-1");expect(streamCalls[1]!.body.message).toContain("continue");expect(credentialResponsePosts()).toHaveLength(0);expect(@@ -679,6 +746,127 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {).toBeTruthy();});+ it("fetches the org credentials on a terminal ask and offers the picker", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ credentialsData.current = [+ { credential_id: "cred_hn", name: "HN login", tested_url: null },+ ];+ await renderChat();+ await submit("who am I signing in as?");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart("turn-9"));+ streamCalls[0]!.onMessage(terminalPromptResponse("turn-9"));+ streamCalls[0]!.resolve();+ });+ // The real card fetches /credentials and surfaces the searchable picker alongside the CTA.+ expect(await screen.findByText("Use existing…")).toBeTruthy();+ expect(apiGet).toHaveBeenCalledWith(+ "/credentials",+ expect.objectContaining({+ params: { page: 1, page_size: 100, credential_type: "password" },+ }),+ );+ });++ it("restores the terminal picker when the auto-continue send fails", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ credentialsData.current = [+ { credential_id: "cred_hn", name: "HN login", tested_url: null },+ ];+ await renderChat();+ await submit("who am I signing in as?");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart("turn-9"));+ streamCalls[0]!.onMessage(terminalPromptResponse("turn-9"));+ streamCalls[0]!.resolve();+ });+ // Pick an existing credential from the terminal picker → the auto-continue send fires.+ await act(async () => {+ fireEvent.click(await screen.findByRole("combobox"));+ });+ await act(async () => {+ fireEvent.click(await screen.findByRole("button", { name: "HN login" }));+ });+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));+ expect(await screen.findByText("Continuing with 'HN login'…")).toBeTruthy();+ // The continuation stream fails.+ await act(async () => {+ streamCalls[1]!.onMessage(turnStart("turn-10"));+ streamCalls[1]!.onMessage(errorFrame("turn-10"));+ streamCalls[1]!.resolve();+ });+ // The optimistic "connected" receipt is rolled back and the picker returns, even though the+ // error message is now the tail — so the user can re-pick instead of hitting a dead end.+ expect(await screen.findByRole("combobox")).toBeTruthy();+ expect(screen.queryByText("Continuing with 'HN login'…")).toBeNull();+ // Re-picking from the restored picker actually resumes: a fresh continuation fires even though+ // the stranded ask is no longer the literal tail.+ await act(async () => {+ fireEvent.click(await screen.findByRole("combobox"));+ });+ await act(async () => {+ fireEvent.click(await screen.findByRole("button", { name: "HN login" }));+ });+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(3));+ });++ it("restores the terminal picker when the auto-continue is cancelled", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ credentialsData.current = [+ { credential_id: "cred_hn", name: "HN login", tested_url: null },+ ];+ await renderChat();+ await submit("who am I signing in as?");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart("turn-9"));+ streamCalls[0]!.onMessage(terminalPromptResponse("turn-9"));+ streamCalls[0]!.resolve();+ });+ await act(async () => {+ fireEvent.click(await screen.findByRole("combobox"));+ });+ await act(async () => {+ fireEvent.click(await screen.findByRole("button", { name: "HN login" }));+ });+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));+ expect(await screen.findByText("Continuing with 'HN login'…")).toBeTruthy();+ // Cancelling the continuation (a cancelled terminal, not an error) must also roll the optimistic+ // receipt back so it doesn't strand a permanent "Continuing…" with no continuation behind it.+ await act(async () => {+ streamCalls[1]!.onMessage(turnStart("turn-10"));+ streamCalls[1]!.onMessage(cancelledContinuationResponse("turn-10"));+ streamCalls[1]!.resolve();+ });+ expect(await screen.findByRole("combobox")).toBeTruthy();+ expect(screen.queryByText("Continuing with 'HN login'…")).toBeNull();+ });++ it("hides a stale terminal ask once it is no longer the last message", async () => {+ flagMap.current = { [COPILOT_UX_V1_FLAG]: true };+ await renderChat();+ await submit("who am I signing in as?");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(turnStart("turn-9"));+ streamCalls[0]!.onMessage(terminalPromptResponse("turn-9"));+ streamCalls[0]!.resolve();+ });+ expect(+ screen.getByRole("button", { name: "Connect credential" }),+ ).toBeTruthy();+ // A new message makes the credential ask non-tail; its actionable card must disappear — picking+ // on a stale card would only show a misleading receipt with no backend call.+ await submit("actually, do something else");+ await waitFor(() =>+ expect(+ screen.queryByRole("button", { name: "Connect credential" }),+ ).toBeNull(),+ );+ });+it("does not auto-continue while a turn is still in flight", async () => {flagMap.current = { [COPILOT_UX_V1_FLAG]: true };await renderChat();diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex f3ffcb7f7..f1ea8093a 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -8,15 +8,10 @@ import {memo,} from "react";import { getClient } from "@/api/AxiosClient";-import {- ActionsApiResponse,- CredentialApiResponse,- getReadableActionType,-} from "@/api/types";+import { ActionsApiResponse, getReadableActionType } from "@/api/types";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { CredentialsModal } from "@/routes/credentials/CredentialsModal";import { CredentialModalTypes } from "@/routes/credentials/useCredentialModalState";-import { getHostname } from "@/util/getHostname";import { useParams } from "react-router-dom";import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";import {@@ -85,7 +80,6 @@ import {type CredentialRequiredFrame,type CredentialRequiredReason,type CredentialPauseHistorical,- type MatchingCredential,} from "./cards/CredentialCard";import {CopilotBlockActionsEvent,@@ -801,14 +795,14 @@ export function WorkflowCopilotChat({const [credentialResolutions, setCredentialResolutions] = useState<Record<string, CredentialResolution>>({});+ // Terminal asks whose auto-continue send failed: the optimistic "connected"+ // receipt is rolled back and the ask is forced actionable again (it is no+ // longer the tail) so the user can re-pick instead of hitting a dead end.+ const [strandedTerminalContinuations, setStrandedTerminalContinuations] =+ useState<ReadonlySet<string>>(() => new Set());const [credentialModalOpen, setCredentialModalOpen] = useState(false);- // Credentials list for matching a live pause against stored credentials.- // Fetched lazily (only once a pause frame arrives — the only path carrying- // login_page_urls to match against), so a chat with no pause never fetches.- const [credentialsList, setCredentialsList] = useState<- CredentialApiResponse[] | null- >(null);- const credentialsFetchInFlight = useRef(false);+ // Bumped when a credential is created so the card's picker re-fetches and includes the new one.+ const [credentialsReloadKey, setCredentialsReloadKey] = useState(0);// Routes the add-credential modal's onCredentialCreated back to the card that// opened it: a live frame (POST resume) or a terminal turn (local resolve).// isLastMessage is captured at open time so a terminal connect only@@ -818,6 +812,10 @@ export function WorkflowCopilotChat({turnId: string;isLastMessage: boolean;} | null>(null);+ // Original ask turnId whose auto-continue send is in flight, so a stream+ // failure can roll its optimistic resolution back. Cleared in handleSend's+ // finally; only one continuation is ever pending (sends are serialized).+ const pendingTerminalContinuation = useRef<string | null>(null);// Latest handleSend for callbacks defined before it (the terminal// auto-continue fires from the modal's onCredentialCreated).const handleSendRef = useRef<((messageOverride?: string) => void) | null>(@@ -1026,67 +1024,12 @@ export function WorkflowCopilotChat({actionPollRef.current.forEach((timer) => clearInterval(timer));actionPollRef.current.clear();}, []);- // Fetch the stored credentials once a pause is live. ponytail: page_size 100,- // no pagination — a >100-credential org may miss a match and fall back to the- // Connect CTA. Add pagination if that shows up. Setting credentialsList back- // to null (after a modal create) re-runs this to pick up the new credential.- useEffect(() => {- if (- !copilotUxV1Enabled ||- !livePauseFrame ||- credentialsList !== null ||- credentialsFetchInFlight.current- ) {- return;- }- credentialsFetchInFlight.current = true;- void (async () => {- try {- const client = await getClient(credentialGetter);- const res = await client.get<CredentialApiResponse[]>("/credentials", {- params: { page: 1, page_size: 100 },- });- setCredentialsList(Array.isArray(res.data) ? res.data : []);- } catch (error) {- // Leave credentialsList null so a later pause frame retries; caching []- // here would disable matching for the whole mounted session.- console.error("Failed to load credentials:", error);- } finally {- credentialsFetchInFlight.current = false;- }- })();- }, [copilotUxV1Enabled, livePauseFrame, credentialsList, credentialGetter]);- const liveMatchingCredentials = useMemo<MatchingCredential[]>(() => {- if (!livePauseFrame) return [];- const toMatch = (- credential: CredentialApiResponse,- ): MatchingCredential => ({- credentialId: credential.credential_id,- name: credential.name,- });- // credential_refs may carry names as well as ids; intersecting on id drops the rest.- const asked = (credentialsList ?? []).filter((credential) =>- livePauseFrame.credential_refs.includes(credential.credential_id),- );- if (asked.length > 0) return asked.map(toMatch);- const hosts = livePauseFrame.login_page_urls- .map(getHostname)- .filter((host): host is string => host !== null);- if (hosts.length === 0) return [];- return (credentialsList ?? [])- .filter((credential) => {- const host = credential.tested_url- ? getHostname(credential.tested_url)- : null;- return host !== null && hosts.includes(host);- })- .map(toMatch);- }, [livePauseFrame, credentialsList]);const respondToCredentialPause = useCallback(async (frame: WorkflowCopilotCredentialRequiredUpdate,action: "connected" | "skip",credentialId?: string,+ name?: string,) => {if (credentialResponseInFlight.current) return;credentialResponseInFlight.current = true;@@ -1100,9 +1043,6 @@ export function WorkflowCopilotChat({action,credential_id: action === "connected" ? credentialId : undefined,});- const name = liveMatchingCredentials.find(- (candidate) => candidate.credentialId === credentialId,- )?.name;setCredentialResolutions((prev) =>withCappedResolution(prev,@@ -1128,7 +1068,7 @@ export function WorkflowCopilotChat({credentialResponseInFlight.current = false;}},- [credentialGetter, liveMatchingCredentials],+ [credentialGetter],);// Terminal-mode cards have no resume_token — connect/skip is a local UI morph,// no network call.@@ -1161,10 +1101,10 @@ export function WorkflowCopilotChat({turnId: string,credentialId: string,name: string | undefined,- isLastMessage: boolean,+ canContinue: boolean,) => {const shouldContinue =- isLastMessage && !isLoading && !isLoadingHistory && Boolean(name);+ canContinue && !isLoading && !isLoadingHistory && Boolean(name);resolveTerminalCredential(turnId,"connected",@@ -1173,13 +1113,42 @@ export function WorkflowCopilotChat({shouldContinue,);if (shouldContinue) {+ pendingTerminalContinuation.current = turnId;+ // Re-attempt: drop any prior stranded flag so the receipt shows again.+ setStrandedTerminalContinuations((prev) => {+ if (!prev.has(turnId)) return prev;+ const next = new Set(prev);+ next.delete(turnId);+ return next;+ });+ // Reference the credential by id: request_policy._explicit_credential_ids resolves a raw cred_+ // id deterministically this turn, avoiding the name-extraction ambiguity a quoted-name reply hits.void handleSendRef.current?.(- `I've connected the credential '${name}' — continue.`,+ `Use the credential ${credentialId} — continue.`,);}},[isLoading, isLoadingHistory, resolveTerminalCredential],);+ // Auto-continue send failed: undo the optimistic "connected" resolution and+ // mark the ask stranded so its card renders actionable again for a retry.+ const rollbackPendingTerminalContinuation = useCallback(() => {+ const turnId = pendingTerminalContinuation.current;+ if (turnId === null) return;+ pendingTerminalContinuation.current = null;+ setCredentialResolutions((prev) => {+ if (!(turnId in prev)) return prev;+ const next = { ...prev };+ delete next[turnId];+ return next;+ });+ setStrandedTerminalContinuations((prev) => {+ if (prev.has(turnId)) return prev;+ const next = new Set(prev);+ next.add(turnId);+ return next;+ });+ }, []);const openCredentialModal = useCallback((frame: WorkflowCopilotCredentialRequiredUpdate | null,@@ -1196,11 +1165,16 @@ export function WorkflowCopilotChat({const ctx = pendingCredentialConnect.current;pendingCredentialConnect.current = null;setCredentialModalOpen(false);- // Re-fetch so the new credential's name resolves in the receipt.- setCredentialsList(null);+ // Refresh the picker's cached list so a still-live ask can offer the just-created credential.+ setCredentialsReloadKey((key) => key + 1);if (!ctx) return;if (ctx.frame) {- void respondToCredentialPause(ctx.frame, "connected", credentialId);+ void respondToCredentialPause(+ ctx.frame,+ "connected",+ credentialId,+ name,+ );} else {continueAfterTerminalConnect(ctx.turnId,@@ -2206,6 +2180,12 @@ export function WorkflowCopilotChat({setMessages((prev) => [...prev, aiMessage]);const userCancelledThisTurn =cancelInFlightController.current === abortController;+ // A genuinely completed continuation keeps its optimistic "connected"+ // receipt; a cancelled one leaves the ref set for the finally to roll+ // back, so a canceled retry doesn't strand a false "Continuing…".+ if (!response.cancelled && !userCancelledThisTurn) {+ pendingTerminalContinuation.current = null;+ }const responseTurnId =response.turn_id ?? latestTurnId.current ?? null;const responseEntry = responseTurnId@@ -2449,6 +2429,10 @@ export function WorkflowCopilotChat({}pendingMessageId.current = null;pendingCancelToken.current = null;+ // Backstop: roll back a continuation that didn't genuinely complete —+ // an error/thrown path already did, but a cancel or abort reaches only+ // here. A no-op once a genuine success cleared the ref above.+ rollbackPendingTerminalContinuation();setIsLoading(false);// Backstop: a turn that ends without a terminal run_outcome (thrown// stream) would otherwise leave a live poll running past the run.@@ -2478,6 +2462,7 @@ export function WorkflowCopilotChat({stopAllRecordedActionsPolls,requiresLiveBrowser,resyncProposalFromChatRow,+ rollbackPendingTerminalContinuation,stopSpeech,takeSpeechAudioBlob,updateQueuedPrompt,@@ -3251,42 +3236,43 @@ export function WorkflowCopilotChat({message.narrative,);if (!credFrame) return null;- // Terminal frames carry no login_page_urls, so there's- // nothing to match against — the only name we can show is- // one captured locally when this turn's pause connected.const localResolution = credentialResolutions[turnId];- const receiptName =- localResolution?.name && localResolution.credentialId- ? [- {- credentialId: localResolution.credentialId,- name: localResolution.name,- },- ]- : undefined;+ const resolvedOutcome =+ localResolution ??+ historicalCredentialOutcome(message.narrative);+ // The actionable ask is only live on the tail message; a resolved receipt still+ // renders on any message so a scrolled-back turn keeps its outcome. Without this,+ // picking on a stale card would show a receipt with no backend call or continue.+ // A stranded ask (its auto-continue failed) stays actionable off-tail for a retry.+ if (+ !resolvedOutcome &&+ !isLastMessage &&+ !strandedTerminalContinuations.has(turnId)+ )+ return null;return (<CredentialCardframe={credFrame}mode="terminal"- matchingCredentials={receiptName}- resolvedOutcome={- localResolution ??- historicalCredentialOutcome(message.narrative)- }+ reloadKey={credentialsReloadKey}+ resolvedOutcome={resolvedOutcome}continued={Boolean(localResolution?.continued)}- // Terminal cards surface no pre-connect matches today,- // so only the modal branch fires; the id branch shares- // the same helper for when terminal mode gains matches.- onConnect={(credentialId) =>- credentialId+ // A picked credential (id + name from the fetched list) auto-continues by+ // id; the Add-credential CTA (no id) opens the modal instead. A stranded ask+ // (its prior continue failed) may continue too, though it is no longer the tail.+ onConnect={(credentialId, name) => {+ const canContinue =+ isLastMessage ||+ strandedTerminalContinuations.has(turnId);+ return credentialId? continueAfterTerminalConnect(turnId,credentialId,- localResolution?.name,- isLastMessage,+ name ?? localResolution?.name,+ canContinue,)- : openCredentialModal(null, turnId, isLastMessage)- }+ : openCredentialModal(null, turnId, canContinue);+ }}onSkip={() =>resolveTerminalCredential(turnId, "skip")}@@ -3412,16 +3398,19 @@ export function WorkflowCopilotChat({<CredentialCardframe={liveFrameToCardFrame(livePauseFrame)}mode="inline-pause"- matchingCredentials={liveMatchingCredentials}+ reloadKey={credentialsReloadKey}resolvedOutcome={credentialResolutions[livePauseFrame.turn_id]}- onConnect={(credentialId) =>+ // A picked credential (id + name from the fetched list) answers through the typed+ // resume POST, which origin-binds; the Add-credential CTA (no id) opens the modal.+ onConnect={(credentialId, name) =>credentialId? void respondToCredentialPause(livePauseFrame,"connected",credentialId,+ name,): openCredentialModal(livePauseFrame,diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.tsindex a7a4917df..0d8666010 100644--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts@@ -1,7 +1,6 @@import type {CredentialPauseHistorical,CredentialRequiredFrame,- MatchingCredential,} from "./CredentialCard";export function buildCredentialRequiredFrame(@@ -67,26 +66,16 @@ export const CREDENTIAL_REQUIRED_FRAME_MINIMAL: CredentialRequiredFrame = {reason: "workflow_credential_inputs_unbound",};-export const NO_MATCHING_CREDENTIALS: MatchingCredential[] = [];--export const ONE_MATCHING_CREDENTIAL: MatchingCredential[] = [- { credentialId: "cred_hn", name: "HN login" },-];--export const TWO_MATCHING_CREDENTIALS: MatchingCredential[] = [- { credentialId: "cred_hn", name: "HN login" },- { credentialId: "cred_acme", name: "Acme portal" },-];--export const MANY_MATCHING_CREDENTIALS: MatchingCredential[] = [- { credentialId: "cred_hn", name: "HN login" },- { credentialId: "cred_acme", name: "Acme portal" },- { credentialId: "cred_qa", name: "QA test account" },-];-export const RESOLVED_OUTCOME_CONNECTED: CredentialPauseHistorical = {outcome: "connected",credentialId: "cred_hn",+ name: "HN login",+};++// A connected outcome whose name never resolved (e.g. a pick the fetch couldn't name).+export const RESOLVED_OUTCOME_CONNECTED_UNNAMED: CredentialPauseHistorical = {+ outcome: "connected",+ credentialId: "cred_hn",};export const RESOLVED_OUTCOME_SKIPPED: CredentialPauseHistorical = {diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsxindex 6b03ed5b6..7dd6e3aab 100644--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx@@ -5,6 +5,7 @@ import {fireEvent,render,screen,+ waitFor,} from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -12,13 +13,10 @@ import {CREDENTIAL_REQUIRED_FRAME_BY_REASON,CREDENTIAL_REQUIRED_FRAME_MINIMAL,CREDENTIAL_REQUIRED_FRAME_NO_MESSAGE,- MANY_MATCHING_CREDENTIALS,- NO_MATCHING_CREDENTIALS,- ONE_MATCHING_CREDENTIAL,RESOLVED_OUTCOME_CONNECTED,+ RESOLVED_OUTCOME_CONNECTED_UNNAMED,RESOLVED_OUTCOME_SKIPPED,RESOLVED_OUTCOME_TIMEOUT,- TWO_MATCHING_CREDENTIALS,buildCredentialRequiredFrame,} from "./CredentialCard.fixtures";import {@@ -28,48 +26,87 @@ import {type CredentialRequiredReason,} from "./CredentialCard";-vi.mock("@/components/ui/select", () => ({- Select: ({+const { getClientMock, credsData, credsFail } = vi.hoisted(() => {+ const data = {+ current: [] as Array<{+ credential_id: string;+ name: string;+ credential_type?: string;+ credential?: { username: string };+ }>,+ };+ const fail = { current: false };+ const get = vi.fn((path: string) =>+ path === "/credentials"+ ? fail.current+ ? Promise.reject(new Error("network"))+ : Promise.resolve({ data: data.current })+ : Promise.resolve({ data: {} }),+ );+ return {+ getClientMock: vi.fn(() => Promise.resolve({ get })),+ credsData: data,+ credsFail: fail,+ };+});++vi.mock("@/api/AxiosClient", () => ({ getClient: getClientMock }));+vi.mock("@/hooks/useCredentialGetter", () => ({+ useCredentialGetter: () => null,+}));++// Radix Popover + cmdk misbehave in jsdom (portals, pointer capture); stub them to plain wrappers so+// the picker's items render inline and are directly clickable, mirroring the Select mock below.+vi.mock("@/components/ui/popover", () => ({+ Popover: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ PopoverTrigger: ({ children }: { children?: ReactNode }) => (+ <div>{children}</div>+ ),+ PopoverContent: ({ children }: { children?: ReactNode }) => (+ <div>{children}</div>+ ),+}));+vi.mock("@/components/ui/command", () => ({+ Command: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ CommandInput: ({ placeholder }: { placeholder?: string }) => (+ <input placeholder={placeholder} />+ ),+ CommandList: ({ children }: { children?: ReactNode }) => (+ <div>{children}</div>+ ),+ CommandEmpty: ({ children }: { children?: ReactNode }) => (+ <div>{children}</div>+ ),+ CommandGroup: ({children,- onValueChange,- disabled,+ heading,}: {children?: ReactNode;- onValueChange?: (value: string) => void;- disabled?: boolean;+ heading?: string;}) => (- <div data-testid="mock-select">- <button- type="button"- data-testid="mock-select-pick-acme"- disabled={disabled}- onClick={() => onValueChange?.("cred_acme")}- >- pick acme (mock)- </button>+ <div>+ {heading ? <div>{heading}</div> : null}{children}</div>),- SelectTrigger: ({ children }: { children?: ReactNode }) => (- <div>{children}</div>- ),- SelectValue: ({ placeholder }: { placeholder?: string }) => (- <span>{placeholder}</span>- ),- SelectContent: ({ children }: { children?: ReactNode }) => (- <div>{children}</div>- ),- SelectItem: ({+ CommandItem: ({children,- value,+ onSelect,}: {children?: ReactNode;- value: string;- }) => <div data-testid={`select-item-${value}`}>{children}</div>,+ onSelect?: () => void;+ value?: string;+ }) => (+ <button type="button" onClick={() => onSelect?.()}>+ {children}+ </button>+ ),}));afterEach(() => {cleanup();+ credsData.current = [];+ credsFail.current = false;vi.clearAllMocks();});@@ -214,132 +251,256 @@ describe("CredentialCard content", () => {});});-describe("CredentialCard secondary slot branching", () => {- it("shows CTA only when no stored credentials match", () => {+describe("CredentialCard callbacks", () => {+ it("calls onConnect(undefined) when the primary CTA is clicked", () => {+ const onConnect = vi.fn();+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ onConnect={onConnect}+ onSkip={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Connect credential" }));+ expect(onConnect).toHaveBeenCalledWith(undefined);+ });++ it("calls onSkip when the dismiss button is clicked", () => {+ const onSkip = vi.fn();+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ onConnect={vi.fn()}+ onSkip={onSkip}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Skip for now" }));+ expect(onSkip).toHaveBeenCalledTimes(1);+ });+});++describe("CredentialCard terminal org-credential picker", () => {+ it("fetches the org credentials and renders them as a picker, in API order", async () => {+ credsData.current = [+ { credential_id: "cred_new", name: "Newest" },+ { credential_id: "cred_old", name: "Oldest" },+ ];render(<CredentialCardframe={buildCredentialRequiredFrame()}mode="terminal"- matchingCredentials={NO_MATCHING_CREDENTIALS}onConnect={vi.fn()}onSkip={vi.fn()}/>,);+ // Most-recent-first is the API's order (created_at desc); the card renders it as-is.+ const newest = await screen.findByRole("button", { name: "Newest" });+ const oldest = screen.getByRole("button", { name: "Oldest" });expect(- screen.getByRole("button", { name: "Connect credential" }),+ newest.compareDocumentPosition(oldest) & Node.DOCUMENT_POSITION_FOLLOWING,).toBeTruthy();- expect(screen.queryByText(/Use '.+'\?/)).toBeNull();- expect(screen.queryByTestId("mock-select")).toBeNull();+ expect(getClientMock).toHaveBeenCalled();+ });++ it("sends the credential id and name when a stored credential is picked", async () => {+ const onConnect = vi.fn();+ credsData.current = [{ credential_id: "cred_hn", name: "HN login" }];+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ onConnect={onConnect}+ onSkip={vi.fn()}+ />,+ );+ fireEvent.click(await screen.findByRole("button", { name: "HN login" }));+ expect(onConnect).toHaveBeenCalledWith("cred_hn", "HN login");});- it("shows a confirm chip when exactly one credential matches", () => {+ it("degrades to the Connect-credential CTA only when the org has no credentials", async () => {render(<CredentialCardframe={buildCredentialRequiredFrame()}mode="terminal"- matchingCredentials={ONE_MATCHING_CREDENTIAL}onConnect={vi.fn()}onSkip={vi.fn()}/>,);+ await waitFor(() => expect(getClientMock).toHaveBeenCalled());expect(- screen.getByRole("button", { name: "Use 'HN login'?" }),+ screen.getByRole("button", { name: "Connect credential" }),).toBeTruthy();- expect(screen.queryByTestId("mock-select")).toBeNull();+ expect(screen.queryByRole("combobox")).toBeNull();});- it("shows a dropdown when several credentials match", () => {+ it("degrades to the CTA when the fetch fails, without caching an empty list", async () => {+ credsFail.current = true;render(<CredentialCardframe={buildCredentialRequiredFrame()}mode="terminal"- matchingCredentials={MANY_MATCHING_CREDENTIALS}onConnect={vi.fn()}onSkip={vi.fn()}/>,);- expect(screen.getByTestId("mock-select")).toBeTruthy();- expect(screen.getByTestId("select-item-cred_hn").textContent).toBe(- "HN login",- );- expect(screen.getByTestId("select-item-cred_acme").textContent).toBe(- "Acme portal",- );- expect(screen.queryByText(/Use '.+'\?/)).toBeNull();+ await waitFor(() => expect(getClientMock).toHaveBeenCalled());+ expect(+ screen.getByRole("button", { name: "Connect credential" }),+ ).toBeTruthy();+ expect(screen.queryByRole("combobox")).toBeNull();});- it("shows a dropdown, not a chip, at exactly two matching credentials", () => {+ it("does not fetch for a terminal receipt (resolved outcome)", () => {render(<CredentialCardframe={buildCredentialRequiredFrame()}mode="terminal"- matchingCredentials={TWO_MATCHING_CREDENTIALS}+ resolvedOutcome={RESOLVED_OUTCOME_CONNECTED}onConnect={vi.fn()}onSkip={vi.fn()}/>,);- expect(screen.getByTestId("mock-select")).toBeTruthy();- expect(screen.queryByText(/Use '.+'\?/)).toBeNull();+ expect(getClientMock).not.toHaveBeenCalled();});-});-describe("CredentialCard callbacks", () => {- it("calls onConnect(undefined) when the primary CTA is clicked", () => {- const onConnect = vi.fn();+ it("labels each row with its username so identical names stay distinguishable", async () => {+ credsData.current = [+ {+ credential_id: "cred_1",+ name: "prod",+ credential_type: "password",+ credential: { username: "[email protected]" },+ },+ {+ credential_id: "cred_2",+ name: "prod",+ credential_type: "password",+ credential: { username: "[email protected]" },+ },+ ];render(<CredentialCardframe={buildCredentialRequiredFrame()}mode="terminal"- onConnect={onConnect}+ onConnect={vi.fn()}onSkip={vi.fn()}/>,);- fireEvent.click(screen.getByRole("button", { name: "Connect credential" }));- expect(onConnect).toHaveBeenCalledWith(undefined);+ expect(await screen.findByText("[email protected]")).toBeTruthy();+ expect(screen.getByText("[email protected]")).toBeTruthy();});- it("calls onConnect(credentialId) when the confirm chip is clicked", () => {- const onConnect = vi.fn();- render(+ it("re-fetches the list when reloadKey changes so a just-created credential appears", async () => {+ credsData.current = [{ credential_id: "cred_old", name: "Old login" }];+ const { rerender } = render(<CredentialCardframe={buildCredentialRequiredFrame()}- mode="terminal"- matchingCredentials={ONE_MATCHING_CREDENTIAL}- onConnect={onConnect}+ mode="inline-pause"+ reloadKey={0}+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(await screen.findByText("Old login")).toBeTruthy();+ // The parent bumps reloadKey after a create; the one-shot fetch must re-run and surface the new one.+ credsData.current = [+ { credential_id: "cred_old", name: "Old login" },+ { credential_id: "cred_new", name: "New login" },+ ];+ rerender(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="inline-pause"+ reloadKey={1}+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(await screen.findByText("New login")).toBeTruthy();+ });++ it("pins the frame's credential_refs under a Suggested group, full list still complete", async () => {+ credsData.current = [+ { credential_id: "cred_sug", name: "Suggested login" },+ { credential_id: "cred_a", name: "Other A" },+ { credential_id: "cred_b", name: "Other B" },+ ];+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame({ credential_refs: ["cred_sug"] })}+ mode="inline-pause"+ onConnect={vi.fn()}onSkip={vi.fn()}/>,);- fireEvent.click(screen.getByRole("button", { name: "Use 'HN login'?" }));- expect(onConnect).toHaveBeenCalledWith("cred_hn");+ expect(await screen.findByText("Suggested")).toBeTruthy();+ expect(screen.getByText("All credentials")).toBeTruthy();+ // Every credential is still present (the suggestion is pinned, not a filter).+ expect(+ screen.getByRole("button", { name: "Suggested login" }),+ ).toBeTruthy();+ expect(screen.getByRole("button", { name: "Other A" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Other B" })).toBeTruthy();});- it("calls onConnect(credentialId) when a dropdown option is picked", () => {+ it("sends the suggested credential's id when it is picked", async () => {const onConnect = vi.fn();+ credsData.current = [+ { credential_id: "cred_sug", name: "Suggested login" },+ { credential_id: "cred_a", name: "Other A" },+ ];render(<CredentialCard- frame={buildCredentialRequiredFrame()}- mode="terminal"- matchingCredentials={MANY_MATCHING_CREDENTIALS}+ frame={buildCredentialRequiredFrame({ credential_refs: ["cred_sug"] })}+ mode="inline-pause"onConnect={onConnect}onSkip={vi.fn()}/>,);- fireEvent.click(screen.getByTestId("mock-select-pick-acme"));- expect(onConnect).toHaveBeenCalledWith("cred_acme");+ fireEvent.click(+ await screen.findByRole("button", { name: "Suggested login" }),+ );+ expect(onConnect).toHaveBeenCalledWith("cred_sug", "Suggested login");});- it("calls onSkip when the dismiss button is clicked", () => {- const onSkip = vi.fn();+ it("renders a plain list with no Suggested group when the frame has no credential_refs", async () => {+ credsData.current = [+ { credential_id: "cred_a", name: "Login A" },+ { credential_id: "cred_b", name: "Login B" },+ ];render(<CredentialCard- frame={buildCredentialRequiredFrame()}+ frame={buildCredentialRequiredFrame({ credential_refs: [] })}mode="terminal"onConnect={vi.fn()}- onSkip={onSkip}+ onSkip={vi.fn()}/>,);- fireEvent.click(screen.getByRole("button", { name: "Skip for now" }));- expect(onSkip).toHaveBeenCalledTimes(1);+ expect(await screen.findByRole("button", { name: "Login A" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Login B" })).toBeTruthy();+ expect(screen.queryByText("Suggested")).toBeNull();+ expect(screen.queryByText("All credentials")).toBeNull();+ });++ it("does not submit a pick after the inline pause has expired", async () => {+ const onConnect = vi.fn();+ credsData.current = [{ credential_id: "cred_a", name: "Login A" }];+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame({+ expires_at: new Date(Date.now() - 1000).toISOString(),+ })}+ mode="inline-pause"+ onConnect={onConnect}+ onSkip={vi.fn()}+ />,+ );+ // The row still renders (the always-open popover mock ignores `open`), but the expiry guard+ // blocks the pick so no already-rejected resume token is submitted.+ fireEvent.click(await screen.findByRole("button", { name: "Login A" }));+ expect(onConnect).not.toHaveBeenCalled();});});@@ -350,21 +511,21 @@ describe("CredentialCard keyboard reachability", () => {// honestly: every interactive control is a legitimate, individually// focusable target (no accidental tabIndex=-1 / non-focusable element),// and a disabled control is correctly excluded.- it("lets every enabled control receive focus individually", () => {+ it("lets every enabled control receive focus individually", async () => {+ credsData.current = [{ credential_id: "cred_hn", name: "HN login" }];render(<CredentialCardframe={buildCredentialRequiredFrame()}- mode="terminal"- matchingCredentials={MANY_MATCHING_CREDENTIALS}+ mode="inline-pause"onConnect={vi.fn()}onSkip={vi.fn()}/>,);+ const picker = await screen.findByRole("combobox");const skip = screen.getByRole("button", { name: "Skip for now" });const connect = screen.getByRole("button", { name: "Connect credential" });- const dropdown = screen.getByTestId("mock-select-pick-acme");- for (const el of [skip, connect, dropdown]) {+ for (const el of [skip, connect, picker]) {el.focus();expect(document.activeElement).toBe(el);}@@ -520,7 +681,6 @@ describe("CredentialCard countdown (inline-pause vs terminal)", () => {<CredentialCardframe={frame}mode="inline-pause"- matchingCredentials={ONE_MATCHING_CREDENTIAL}onConnect={onConnect}onSkip={onSkip}/>,@@ -533,14 +693,11 @@ describe("CredentialCard countdown (inline-pause vs terminal)", () => {const connectButton = screen.getByRole("button", {name: "Connect credential",});- const chipButton = screen.getByRole("button", { name: "Use 'HN login'?" });const skipButton = screen.getByRole("button", { name: "Skip for now" });expect(connectButton.hasAttribute("disabled")).toBe(true);- expect(chipButton.hasAttribute("disabled")).toBe(true);expect(skipButton.hasAttribute("disabled")).toBe(true);fireEvent.click(connectButton);- fireEvent.click(chipButton);fireEvent.click(skipButton);expect(onConnect).not.toHaveBeenCalled();expect(onSkip).not.toHaveBeenCalled();@@ -641,7 +798,6 @@ describe("CredentialCard historical (resolvedOutcome) rendering", () => {<CredentialCardframe={buildCredentialRequiredFrame()}mode="terminal"- matchingCredentials={ONE_MATCHING_CREDENTIAL}resolvedOutcome={RESOLVED_OUTCOME_CONNECTED}onConnect={onConnect}onSkip={onSkip}@@ -660,7 +816,6 @@ describe("CredentialCard historical (resolvedOutcome) rendering", () => {<CredentialCardframe={buildCredentialRequiredFrame()}mode="terminal"- matchingCredentials={ONE_MATCHING_CREDENTIAL}resolvedOutcome={RESOLVED_OUTCOME_CONNECTED}continuedonConnect={vi.fn()}@@ -676,8 +831,7 @@ describe("CredentialCard historical (resolvedOutcome) rendering", () => {<CredentialCardframe={buildCredentialRequiredFrame()}mode="terminal"- matchingCredentials={NO_MATCHING_CREDENTIALS}- resolvedOutcome={RESOLVED_OUTCOME_CONNECTED}+ resolvedOutcome={RESOLVED_OUTCOME_CONNECTED_UNNAMED}continuedonConnect={vi.fn()}onSkip={vi.fn()}@@ -691,8 +845,7 @@ describe("CredentialCard historical (resolvedOutcome) rendering", () => {<CredentialCardframe={buildCredentialRequiredFrame()}mode="terminal"- matchingCredentials={NO_MATCHING_CREDENTIALS}- resolvedOutcome={RESOLVED_OUTCOME_CONNECTED}+ resolvedOutcome={RESOLVED_OUTCOME_CONNECTED_UNNAMED}onConnect={vi.fn()}onSkip={vi.fn()}/>,diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsxindex 40c72cfd1..cbfe8411c 100644--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx@@ -1,13 +1,27 @@-import { useEffect, useState } from "react";-import { Cross2Icon, LockClosedIcon } from "@radix-ui/react-icons";+import { useEffect, useRef, useState } from "react";+import {+ ChevronDownIcon,+ Cross2Icon,+ LockClosedIcon,+} from "@radix-ui/react-icons";+import { getClient } from "@/api/AxiosClient";+import { isPasswordCredential, type CredentialApiResponse } from "@/api/types";+import { Button } from "@/components/ui/button";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command";import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { useCredentialGetter } from "@/hooks/useCredentialGetter";// Union of both a request-policy-time classifier's real reason tokens and a// mid-build run-failure reason that isn't emitted by any shipped backend@@ -44,26 +58,34 @@ export type CredentialPauseOutcome = "connected" | "skipped" | "timeout";export interface CredentialPauseHistorical {outcome: CredentialPauseOutcome;credentialId?: string;+ // Captured at connect time so the receipt names the credential without a lookup.+ name?: string;}-export interface MatchingCredential {+// A picker row: id/name plus a secondary discriminator (the login username) so two credentials+// saved under the same name stay distinguishable.+interface PickerCredential {credentialId: string;name: string;+ secondary?: string;}export interface CredentialCardProps {frame: CredentialRequiredFrame;mode: CredentialCardMode;- matchingCredentials?: MatchingCredential[];resolvedOutcome?: CredentialPauseHistorical;// undefined = primary CTA (wiring opens the add-credential modal); a string- // id = the user picked an already-stored credential (chip or dropdown).- onConnect: (credentialId?: string) => void;+ // id = the user picked an already-stored credential. name rides along so the+ // receipt shows it and the resume/continue references it without a lookup.+ onConnect: (credentialId?: string, name?: string) => void;onSkip: () => void;// Terminal connect auto-sends a "continue" turn; the receipt says so instead// of the plain "added". Defaults false so inline-pause and every other caller// keep the existing copy.continued?: boolean;+ // Bumped by the parent when a credential is created so the one-shot fetch re-runs and the new+ // credential shows up in the picker (e.g. if the resume POST failed and the ask is still live).+ reloadKey?: number;}const SIGN_IN_WHY_LINE =@@ -171,14 +193,99 @@ function CredentialSystemRow({ text }: { text: string }) {);}+// Searchable picker over the whole org credential list. Built on the cmdk primitives (same pattern as+// the workflow-builder CredentialCombobox) rather than importing it, since that one pulls react-query+// and the copilot chat's test harness has no QueryClientProvider.+function CredentialPicker({+ credentials,+ suggestedIds,+ disabled,+ onPick,+}: {+ credentials: PickerCredential[];+ // Copilot's suggested candidates for this sign-in (only inline-pause frames carry them; terminal+ // asks deliberately don't stamp payload candidates, so they show a plain list).+ suggestedIds?: string[];+ disabled?: boolean;+ onPick: (credentialId: string, name: string) => void;+}) {+ const [open, setOpen] = useState(false);+ const suggestedSet = new Set(suggestedIds ?? []);+ const suggested = credentials.filter((c) => suggestedSet.has(c.credentialId));+ const rest = credentials.filter((c) => !suggestedSet.has(c.credentialId));+ const renderItem = (credential: PickerCredential) => (+ <CommandItem+ key={credential.credentialId}+ // cmdk filters on value; append username + id so identical names stay findable.+ value={`${credential.name} ${credential.secondary ?? ""} ${credential.credentialId}`}+ onSelect={() => {+ // A pick after the pause expires would submit an already-rejected resume token; the popover+ // closes on `disabled` above, this guards a click already in flight.+ if (disabled) return;+ setOpen(false);+ onPick(credential.credentialId, credential.name);+ }}+ >+ <div className="flex min-w-0 flex-col">+ <span className="truncate">{credential.name}</span>+ {credential.secondary ? (+ <span className="truncate text-[11px] text-muted-foreground">+ {credential.secondary}+ </span>+ ) : null}+ </div>+ </CommandItem>+ );+ return (+ <Popover open={open && !disabled} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <Button+ type="button"+ role="combobox"+ aria-expanded={open}+ variant="outline"+ disabled={disabled}+ className="h-6 w-[200px] justify-between px-3 text-xs font-normal"+ >+ <span className="truncate">Use existing…</span>+ <ChevronDownIcon className="ml-2 size-3 shrink-0 opacity-50" />+ </Button>+ </PopoverTrigger>+ <PopoverContent+ className="w-[var(--radix-popover-trigger-width)] p-0"+ align="start"+ >+ <Command>+ <CommandInput placeholder="Search credentials..." />+ <CommandList>+ <CommandEmpty>No credentials found.</CommandEmpty>+ {suggested.length > 0 ? (+ // Copilot's suggestion(s) pinned first; cmdk highlights the first item, so one Enter+ // accepts it. The full org list stays below to override.+ <CommandGroup heading="Suggested">+ {suggested.map(renderItem)}+ </CommandGroup>+ ) : null}+ <CommandGroup+ heading={suggested.length > 0 ? "All credentials" : undefined}+ >+ {rest.map(renderItem)}+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ );+}+export function CredentialCard({frame,mode,- matchingCredentials = [],resolvedOutcome,onConnect,onSkip,continued = false,+ reloadKey,}: Readonly<CredentialCardProps>) {// Terminal mode never expires by design: its signal carries no timeout/expiry// semantics at all, so there is nothing to compare "now" against. Only a@@ -191,6 +298,52 @@ export function CredentialCard({);const disabled = countdownActive && expired;+ const credentialGetter = useCredentialGetter();+ const [orgCredentials, setOrgCredentials] = useState<+ PickerCredential[] | null+ >(null);+ const fetchGeneration = useRef(0);+ // Any credential ask (terminal or inline-pause) lists every org login credential so the user can+ // pick or create. credential_type=password since the card only ever asks for a sign-in; the API+ // returns them most-recent-first (created_at desc), used as-is. Direct getClient fetch, not+ // useCredentialsQuery: the copilot chat's test harness has no QueryClientProvider. Re-fetches when+ // the parent bumps reloadKey (a credential was just created) so the new one appears in the picker.+ // page_size 100 with no pagination — a >100-credential org shows only the 100 most-recent; older+ // ones are reachable only by creating a new credential. Add the route's `search` param if that bites.+ const isAsk = !resolvedOutcome;+ useEffect(() => {+ if (!isAsk) return;+ // Generation guard: a fetch superseded by a reloadKey change (or a slow one) must not set state+ // after a newer fetch has started, so a stale response can't overwrite the current list.+ const generation = ++fetchGeneration.current;+ void (async () => {+ try {+ const client = await getClient(credentialGetter);+ const res = await client.get<CredentialApiResponse[]>("/credentials", {+ params: { page: 1, page_size: 100, credential_type: "password" },+ });+ if (fetchGeneration.current !== generation) return;+ setOrgCredentials(+ (Array.isArray(res.data) ? res.data : []).map((credential) => ({+ credentialId: credential.credential_id,+ name: credential.name,+ secondary:+ credential.credential &&+ isPasswordCredential(credential.credential)+ ? credential.credential.username+ : undefined,+ })),+ );+ } catch (error) {+ // Leave the list null so the picker degrades to the Connect-credential CTA; null keeps+ // not-loaded distinct from a genuinely empty org.+ if (fetchGeneration.current === generation) {+ console.error("Failed to load credentials:", error);+ }+ }+ })();+ }, [isAsk, reloadKey, credentialGetter]);+if (resolvedOutcome) {switch (resolvedOutcome.outcome) {case "skipped":@@ -198,10 +351,7 @@ export function CredentialCard({case "timeout":return <CredentialSystemRow text={TIMEOUT_COPY} />;case "connected": {- const name = matchingCredentials.find(- (credential) =>- credential.credentialId === resolvedOutcome.credentialId,- )?.name;+ const name = resolvedOutcome.name;const heading = continued? name? `Continuing with '${name}'…`@@ -235,9 +385,6 @@ export function CredentialCard({}const site = siteFromLoginPageUrls(frame.login_page_urls);- const singleMatch =- matchingCredentials.length === 1 ? matchingCredentials[0] : null;- const multipleMatches = matchingCredentials.length >= 2;return (<div>@@ -302,35 +449,13 @@ export function CredentialCard({>Connect credential</button>- {singleMatch ? (- <button- type="button"+ {orgCredentials && orgCredentials.length > 0 ? (+ <CredentialPicker+ credentials={orgCredentials}+ suggestedIds={frame.credential_refs}disabled={disabled}- onClick={() => onConnect(singleMatch.credentialId)}- className="rounded-md border border-border px-3 py-1 text-xs text-muted-foreground hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50"- >- Use '{singleMatch.name}'?- </button>- ) : null}- {multipleMatches ? (- <Select- disabled={disabled}- onValueChange={(credentialId) => onConnect(credentialId)}- >- <SelectTrigger className="h-7 w-[170px] text-xs">- <SelectValue placeholder="Use existing…" />- </SelectTrigger>- <SelectContent>- {matchingCredentials.map((credential) => (- <SelectItem- key={credential.credentialId}- value={credential.credentialId}- >- {credential.name}- </SelectItem>- ))}- </SelectContent>- </Select>+ onPick={(credentialId, name) => onConnect(credentialId, name)}+ />) : null}</div></div>diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex b356bda6e..29d5c4741 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -4520,19 +4520,10 @@ def _output_policy_diagnostics_from_guardrail_exception(exc: BaseException) -> dreturn {key: data[key] for key in keys if key in data}-def _unapproved_credential_reference_reply(request_policy: RequestPolicy | None) -> str:- resolution = request_policy.live_page_resolution if request_policy is not None else None- if resolution is not None and resolution.verdict == "ambiguous" and resolution.candidates:- listed = "; ".join(f"{candidate.name} (`{candidate.credential_id}`)" for candidate in resolution.candidates)- # The Credentials UI marker has to survive on this branch too: credential_prompt_reason keys- # the FE credential card off it, so dropping it silently removes the card for ambiguous asks.- return (- f"More than one saved credential is set up for the sign-in page I reached: {listed}. "- "Reply with the credential ID you want me to use, manage them in the Credentials UI, "- "or adjust the workflow to avoid using credentials."- )- # Only the observation seam records a verdict, so the absence of one says nothing about whether a- # credential matched — claiming "no match" here would deny a real match found at the fill seam.+def _unapproved_credential_reference_reply() -> str:+ # "Credentials UI" is a credential_prompt_reason() text marker the FE credential card keys off, so+ # this reply must keep it verbatim. One sentence, no candidate enumeration: the card renders the+ # full org credential selector, so listing matches here would be a redundant prose dump.return ("I need an approved credential to continue. Reply with the credential ID to use, ""add one in the Credentials UI, or adjust the workflow to avoid using credentials."@@ -4579,7 +4570,7 @@ def _build_output_policy_blocked_result(user_response = _RAW_SECRET_LEAK_REFUSALadd_saved_draft_copy = Trueelif OutputPolicyReason.UNAPPROVED_CREDENTIAL_REFERENCE in verdict.reason_codes:- user_response = _unapproved_credential_reference_reply(request_policy)+ user_response = _unapproved_credential_reference_reply()add_saved_draft_copy = Trueelif OutputPolicyReason.CREDENTIAL_SCOPE_BROADENED in verdict.reason_codes:user_response = (diff --git a/skyvern/forge/sdk/copilot/credential_pause.py b/skyvern/forge/sdk/copilot/credential_pause.pyindex 34d8ec0be..5b8a5fb90 100644--- a/skyvern/forge/sdk/copilot/credential_pause.py+++ b/skyvern/forge/sdk/copilot/credential_pause.py@@ -469,6 +469,8 @@ async def _run_credential_pause(policy = getattr(ctx, "request_policy", None)login_page_urls = list(policy.login_page_urls) if isinstance(policy, RequestPolicy) else []+ # The FE credential card fetches the full org list itself; these ride the frame as `credential_refs`+ # and seed the picker's "Suggested" group (pinned first), so the user still sees the full list.credential_refs: list[str] = []if isinstance(policy, RequestPolicy):credential_refs = list(policy.credential_ask_candidate_ids or policy.credential_refs)diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex dd813f993..84061f354 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -214,7 +214,9 @@ _INVALID_CONDITIONAL_CONTAINER_MARKERS = ("inside conditional","within conditional",)-_QUOTED_CREDENTIAL_NAME_RE = re.compile(r"(?:`([^`]{1,100})`|\"([^\"]{1,100})\"|'([^']{1,100})')")+# The leading (?<!\w) keeps a contraction's apostrophe ("I've", "can't") from opening a quote and+# pairing with a later one, which would swallow the run between them as a bogus credential name.+_QUOTED_CREDENTIAL_NAME_RE = re.compile(r"(?:`([^`]{1,100})`|\"([^\"]{1,100})\"|(?<!\w)'([^']{1,100})')")_NAMED_CREDENTIAL_TOKEN_RE = re.compile(r"\b(?:saved\s+credential|credential)\s+(?:named|called)\s+([A-Za-z0-9_.@:-]{2,100})\b",re.I,@@ -4560,17 +4562,9 @@ def _block(if reason is not None:policy.clarification_reason = reasonpolicy.credential_ask_card_answerable = card_answerable+ # Candidate ids ride the pause frame as BE machinery; the card renders the full-org picker, so+ # the ask never enumerates credentials in prose.policy.credential_ask_candidate_ids = [candidate.credential_id for candidate in candidates or []]- if candidates:- # "Safe" is a claim about the login page vouching for each candidate, so it only holds- # when the ask had a page to match against and every candidate was tested against one.- matched_by_url = bool(policy.credential_ask_login_page_urls) and all(- candidate.tested_url for candidate in candidates- )- label = "Safe matches" if matched_by_url else "Saved credentials"- question += f"\n\n{label}:\n" + "\n".join(- f"- {credential_candidate_label(candidate)}" for candidate in candidates- )policy.clarification_question = questiondiff --git a/tests/unit/test_copilot_agent_blocker_renderer.py b/tests/unit/test_copilot_agent_blocker_renderer.pyindex c4674899b..a208f84b4 100644--- a/tests/unit/test_copilot_agent_blocker_renderer.py+++ b/tests/unit/test_copilot_agent_blocker_renderer.py@@ -1029,7 +1029,7 @@ def test_unapproved_credential_reference_asks_without_naming_the_credential_inveassert "hr portal" not in result.user_response-def test_unapproved_credential_reference_lists_both_ambiguous_candidate_ids() -> None:+def test_unapproved_credential_reference_ambiguous_does_not_enumerate_candidates() -> None:ctx = _ctx()ctx.request_policy = RequestPolicy(live_page_resolution=LivePageResolutionRecord(@@ -1044,9 +1044,12 @@ def test_unapproved_credential_reference_lists_both_ambiguous_candidate_ids() ->result = _blocked_result(ctx, OutputPolicyReason.UNAPPROVED_CREDENTIAL_REFERENCE)- assert "cred_first" in result.user_response- assert "cred_second" in result.user_response- assert "credential ID" in result.user_response+ # The ambiguous branch used to list candidate ids; the FE now renders the full org selector, so the+ # reply is one sentence with the Credentials UI marker and no prose dump.+ assert "I need an approved credential to continue" in result.user_response+ assert "Credentials UI" in result.user_response+ assert "cred_first" not in result.user_response+ assert "cred_second" not in result.user_responsedef test_unapproved_credential_reference_points_at_credentials_ui_when_nothing_matched() -> None:diff --git a/tests/unit/test_copilot_request_policy_workflow_credentials.py b/tests/unit/test_copilot_request_policy_workflow_credentials.pyindex 38eea24bb..3a2b64dd7 100644--- a/tests/unit/test_copilot_request_policy_workflow_credentials.py+++ b/tests/unit/test_copilot_request_policy_workflow_credentials.py@@ -32,6 +32,7 @@ from skyvern.forge.sdk.copilot.request_policy import (_can_defer_unresolved_credential_name_for_draft,_classification_from_raw,_clean_email_list,+ _exact_credential_name_candidates,_resolve_credentials,_saved_credential_names_mentioned,_seed_prior_approved_credentials,@@ -1030,11 +1031,12 @@ async def test_multiple_name_hits_keep_the_existing_picker_and_skip_url() -> Non)assert policy.requires_user_clarification is True- assert policy.clarification_question is not None- assert policy.clarification_question.startswith(- "I found multiple stored credentials with that exact name. Which one should I use?"+ assert (+ policy.clarification_question+ == "I found multiple stored credentials with that exact name. Which one should I use?")- assert "`cred_url`" not in policy.clarification_question+ # No prose credential dump: neither the named matches nor the unrelated URL cred are listed.+ assert "cred_" not in policy.clarification_questionload_mock.assert_awaited_once()@@ -1061,8 +1063,11 @@ async def test_name_collision_candidates_are_not_labelled_safe_matches() -> None)assert policy.clarification_question is not None- assert "Saved credentials:" in policy.clarification_question+ # No prose enumeration at all — the card renders the full-org picker, so candidates are never+ # labelled (neither "Safe matches" nor "Saved credentials"); they ride on the policy field.+ assert "Saved credentials" not in policy.clarification_questionassert "Safe matches" not in policy.clarification_question+ assert policy.credential_ask_candidate_ids == ["cred_one", "cred_two"]assert policy.credential_ask_login_page_urls == []@@ -1082,10 +1087,11 @@ async def test_url_tier_deduplicates_and_keeps_existing_picker() -> None:org_credentials=[first, first, second],)- assert policy.clarification_question is not None- assert policy.clarification_question.startswith(_AMBIGUOUS_URL_CREDENTIAL_QUESTION)- assert policy.clarification_question.count("`cred_first`") == 1- assert policy.clarification_question.count("`cred_second`") == 1+ assert policy.clarification_question == _AMBIGUOUS_URL_CREDENTIAL_QUESTION+ # The "Safe matches" prose dump is gone; the deduplicated candidate set now rides only on+ # discovered_credentials (the FE renders the full org selector instead of a text list).+ assert {c.credential_id for c in policy.discovered_credentials} == {"cred_first", "cred_second"}+ assert len(policy.discovered_credentials) == 2load_mock.assert_awaited_once()@@ -1435,12 +1441,10 @@ async def test_website_kind_multiple_url_less_credentials_ask_which_one() -> Non)assert policy.requires_user_clarification is True- assert policy.clarification_question is not None- assert policy.clarification_question.startswith(_AMBIGUOUS_URLLESS_CREDENTIAL_QUESTION)- assert "Safe matches" not in policy.clarification_question- assert "for that login page" not in policy.clarification_question- assert "first-login" in policy.clarification_question- assert "second-login" in policy.clarification_question+ # One clean sentence, no prose credential dump; candidates ride on discovered_credentials / candidate_ids.+ assert policy.clarification_question == _AMBIGUOUS_URLLESS_CREDENTIAL_QUESTION+ assert "first-login" not in policy.clarification_question+ assert "second-login" not in policy.clarification_questionassert policy.clarification_reason == "credential_name_unresolved"assert sorted(c.credential_id for c in policy.discovered_credentials) == ["cred_one", "cred_two"]assert not policy.resolved_credentials@@ -1466,9 +1470,8 @@ async def test_website_kind_multiple_url_matches_keep_disambiguation_reason() ->],)- assert policy.clarification_question is not None- assert policy.clarification_question.startswith(_AMBIGUOUS_URL_CREDENTIAL_QUESTION)- assert "Safe matches:" in policy.clarification_question+ # One clean sentence, no prose credential dump; candidates ride on discovered_credentials.+ assert policy.clarification_question == _AMBIGUOUS_URL_CREDENTIAL_QUESTIONassert policy.clarification_reason == "credential_name_unresolved"assert policy.credential_ask_card_answerable is Trueassert sorted(c.credential_id for c in policy.discovered_credentials) == ["cred_one", "cred_two"]@@ -1787,13 +1790,9 @@ async def test_login_intent_none_kind_multiple_host_matches_asks_pick_question()assert policy.credential_input_kind == "none"assert policy.requires_user_clarification is True- assert policy.clarification_question is not None- assert (- "I found multiple stored credentials for that login page. Which one should I use?"- in policy.clarification_question- )- assert "`cred_a`" in policy.clarification_question- assert "`cred_b`" in policy.clarification_question+ # One clean sentence, no prose credential dump; the candidate set rides on discovered_credentials.+ assert policy.clarification_question == _AMBIGUOUS_URL_CREDENTIAL_QUESTION+ assert {c.credential_id for c in policy.discovered_credentials} == {"cred_a", "cred_b"}assert policy.clarification_reason == "credential_name_unresolved"@@ -2761,6 +2760,15 @@ def test_a_named_credential_resolves_without_the_word_credential() -> None:assert _saved_credential_names_mentioned("use skyvern-datadog to login.", credentials) == ["skyvern-datadog"]+def test_contraction_apostrophe_does_not_open_a_bogus_quoted_name() -> None:+ """A contraction's apostrophe once paired with a later quote and swallowed the span between them as+ a credential name (e.g. from "I've connected the credential 'hex'"). It must extract only 'hex'."""+ candidates = _exact_credential_name_candidates("I've connected the credential 'hex' — continue.")++ assert "hex" in candidates+ assert not any("connected" in candidate for candidate in candidates)++@pytest.mark.asyncioasync def test_a_named_credential_resolves_when_the_classifier_misses_login_intent() -> None:"""`login_intent` is a model-authored hint that varies run to run. Gating the saved-name scan on