Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-12139): add isolated copilot credential card component (#7274)
Celal Zamanoğlueefba9c90b22
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.tsnew file mode 100644index 000000000..a7a4917df--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.fixtures.ts@@ -0,0 +1,98 @@+import type {+ CredentialPauseHistorical,+ CredentialRequiredFrame,+ MatchingCredential,+} from "./CredentialCard";++export function buildCredentialRequiredFrame(+ overrides: Partial<CredentialRequiredFrame> = {},+): CredentialRequiredFrame {+ return {+ type: "credential_required",+ turn_id: "turn_123",+ workflow_copilot_chat_id: "wcc_123",+ reason: "workflow_credential_inputs_unbound",+ message:+ "The draft is ready, but news.ycombinator.com needs a login before I can test-run it.",+ login_page_urls: ["https://news.ycombinator.com/login"],+ credential_refs: [],+ timeout_seconds: 300,+ expires_at: new Date(Date.now() + 300_000).toISOString(),+ timestamp: new Date().toISOString(),+ ...overrides,+ };+}++export const CREDENTIAL_REQUIRED_FRAME_BY_REASON = {+ workflow_credential_inputs_unbound: buildCredentialRequiredFrame({+ reason: "workflow_credential_inputs_unbound",+ }),+ credential_name_unresolved: buildCredentialRequiredFrame({+ reason: "credential_name_unresolved",+ message: undefined,+ }),+ credential_invention_requested: buildCredentialRequiredFrame({+ reason: "credential_invention_requested",+ message: undefined,+ }),+ raw_secret: buildCredentialRequiredFrame({+ reason: "raw_secret",+ message: undefined,+ }),+ assistant_directed: buildCredentialRequiredFrame({+ reason: "assistant_directed",+ message: undefined,+ }),+ missing_credential_run_failure: buildCredentialRequiredFrame({+ reason: "missing_credential_run_failure",+ message: "The last run stopped at the Hacker News login step.",+ }),+ credential_deferred_draft: buildCredentialRequiredFrame({+ reason: "credential_deferred_draft",+ message: "Picking back up on the credential you held off on earlier.",+ }),+} as const;++// No dynamic ask text; only a richer, timed pause signal supplies one.+export const CREDENTIAL_REQUIRED_FRAME_NO_MESSAGE: CredentialRequiredFrame =+ buildCredentialRequiredFrame({+ reason: "credential_name_unresolved",+ message: undefined,+ });++// Mirrors a minimal request-policy-time classifier signal exactly: only+// `type` and `reason` are ever guaranteed, everything else is undefined.+export const CREDENTIAL_REQUIRED_FRAME_MINIMAL: CredentialRequiredFrame = {+ type: "credential_required",+ 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",+};++export const RESOLVED_OUTCOME_SKIPPED: CredentialPauseHistorical = {+ outcome: "skipped",+};++export const RESOLVED_OUTCOME_TIMEOUT: CredentialPauseHistorical = {+ outcome: "timeout",+};diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsxnew file mode 100644index 000000000..ffa3edef0--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx@@ -0,0 +1,675 @@+import type { ReactNode } from "react";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++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_SKIPPED,+ RESOLVED_OUTCOME_TIMEOUT,+ TWO_MATCHING_CREDENTIALS,+ buildCredentialRequiredFrame,+} from "./CredentialCard.fixtures";+import {+ CREDENTIAL_WHY_LINE_BY_REASON,+ CredentialCard,+ type CredentialPauseHistorical,+ type CredentialRequiredReason,+} from "./CredentialCard";++vi.mock("@/components/ui/select", () => ({+ Select: ({+ children,+ onValueChange,+ disabled,+ }: {+ children?: ReactNode;+ onValueChange?: (value: string) => void;+ disabled?: boolean;+ }) => (+ <div data-testid="mock-select">+ <button+ type="button"+ data-testid="mock-select-pick-acme"+ disabled={disabled}+ onClick={() => onValueChange?.("cred_acme")}+ >+ pick acme (mock)+ </button>+ {children}+ </div>+ ),+ SelectTrigger: ({ children }: { children?: ReactNode }) => (+ <div>{children}</div>+ ),+ SelectValue: ({ placeholder }: { placeholder?: string }) => (+ <span>{placeholder}</span>+ ),+ SelectContent: ({ children }: { children?: ReactNode }) => (+ <div>{children}</div>+ ),+ SelectItem: ({+ children,+ value,+ }: {+ children?: ReactNode;+ value: string;+ }) => <div data-testid={`select-item-${value}`}>{children}</div>,+}));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("CredentialCard content", () => {+ it("renders the site parsed from login_page_urls in the headline", () => {+ const frame = buildCredentialRequiredFrame({+ login_page_urls: ["https://news.ycombinator.com/login?goto=news"],+ });+ render(+ <CredentialCard+ frame={frame}+ mode="terminal"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(+ screen.getByText("Copilot needs to sign in to news.ycombinator.com"),+ ).toBeTruthy();+ });++ it("falls back to a generic site label when login_page_urls is empty", () => {+ const frame = buildCredentialRequiredFrame({ login_page_urls: [] });+ render(+ <CredentialCard+ frame={frame}+ mode="terminal"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(+ screen.getByText("Copilot needs to sign in to the site"),+ ).toBeTruthy();+ });++ it("falls back to the raw string when login_page_urls[0] isn't a parseable URL", () => {+ const frame = buildCredentialRequiredFrame({+ login_page_urls: ["not a valid url"],+ });+ render(+ <CredentialCard+ frame={frame}+ mode="terminal"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(+ screen.getByText("Copilot needs to sign in to not a valid url"),+ ).toBeTruthy();+ });++ it("renders the frame message as lead prose", () => {+ const frame = buildCredentialRequiredFrame({+ message: "Custom ask text for this turn.",+ });+ render(+ <CredentialCard+ frame={frame}+ mode="terminal"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(screen.getByText("Custom ask text for this turn.")).toBeTruthy();+ });++ it("renders no lead paragraph when the frame has no message (today's credentialPrompt shape)", () => {+ const { container } = render(+ <CredentialCard+ frame={CREDENTIAL_REQUIRED_FRAME_NO_MESSAGE}+ mode="terminal"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(container.querySelector("p.text-sm")).toBeNull();+ expect(+ screen.getByText("Copilot needs to sign in to news.ycombinator.com"),+ ).toBeTruthy();+ });++ it("renders from a minimal frame carrying only type and reason", () => {+ const onConnect = vi.fn();+ render(+ <CredentialCard+ frame={CREDENTIAL_REQUIRED_FRAME_MINIMAL}+ mode="terminal"+ onConnect={onConnect}+ onSkip={vi.fn()}+ />,+ );+ expect(+ screen.getByText("Copilot needs to sign in to the site"),+ ).toBeTruthy();+ expect(+ screen.getByText(+ CREDENTIAL_WHY_LINE_BY_REASON.workflow_credential_inputs_unbound,+ ),+ ).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Connect credential" }));+ expect(onConnect).toHaveBeenCalledWith(undefined);+ });++ it.each(+ Object.keys(CREDENTIAL_WHY_LINE_BY_REASON) as CredentialRequiredReason[],+ )("renders the reason-mapped why-line for %s", (reason) => {+ const frame = CREDENTIAL_REQUIRED_FRAME_BY_REASON[reason];+ render(+ <CredentialCard+ frame={frame}+ mode="terminal"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(+ screen.getByText(CREDENTIAL_WHY_LINE_BY_REASON[reason]),+ ).toBeTruthy();+ });++ it("falls back to the generic sign-in why-line for an out-of-union reason value", () => {+ // Simulates a backend reason token shipped ahead of a frontend update —+ // the type cast is the point of the test.+ const frame = buildCredentialRequiredFrame({+ reason: "future_unknown_reason" as CredentialRequiredReason,+ });+ render(+ <CredentialCard+ frame={frame}+ mode="terminal"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(+ screen.getByText(+ CREDENTIAL_WHY_LINE_BY_REASON.workflow_credential_inputs_unbound,+ ),+ ).toBeTruthy();+ });+});++describe("CredentialCard secondary slot branching", () => {+ it("shows CTA only when no stored credentials match", () => {+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ matchingCredentials={NO_MATCHING_CREDENTIALS}+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(+ screen.getByRole("button", { name: "Connect credential" }),+ ).toBeTruthy();+ expect(screen.queryByText(/Use '.+'\?/)).toBeNull();+ expect(screen.queryByTestId("mock-select")).toBeNull();+ });++ it("shows a confirm chip when exactly one credential matches", () => {+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ matchingCredentials={ONE_MATCHING_CREDENTIAL}+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(+ screen.getByRole("button", { name: "Use 'HN login'?" }),+ ).toBeTruthy();+ expect(screen.queryByTestId("mock-select")).toBeNull();+ });++ it("shows a dropdown when several credentials match", () => {+ render(+ <CredentialCard+ frame={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();+ });++ it("shows a dropdown, not a chip, at exactly two matching credentials", () => {+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ matchingCredentials={TWO_MATCHING_CREDENTIALS}+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(screen.getByTestId("mock-select")).toBeTruthy();+ expect(screen.queryByText(/Use '.+'\?/)).toBeNull();+ });+});++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 onConnect(credentialId) when the confirm chip is clicked", () => {+ const onConnect = vi.fn();+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ matchingCredentials={ONE_MATCHING_CREDENTIAL}+ onConnect={onConnect}+ onSkip={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Use 'HN login'?" }));+ expect(onConnect).toHaveBeenCalledWith("cred_hn");+ });++ it("calls onConnect(credentialId) when a dropdown option is picked", () => {+ const onConnect = vi.fn();+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ matchingCredentials={MANY_MATCHING_CREDENTIALS}+ onConnect={onConnect}+ onSkip={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByTestId("mock-select-pick-acme"));+ expect(onConnect).toHaveBeenCalledWith("cred_acme");+ });++ 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 keyboard reachability", () => {+ // jsdom doesn't move focus on a synthetic Tab keypress the way a real+ // browser does, so this can't honestly simulate Tab traversal — that was+ // verified with real CDP-driven input in DESIGN-OUT. What this CAN pin+ // 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", () => {+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ matchingCredentials={MANY_MATCHING_CREDENTIALS}+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ 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]) {+ el.focus();+ expect(document.activeElement).toBe(el);+ }+ });++ it("excludes a disabled control from receiving focus", () => {+ const frame = buildCredentialRequiredFrame({+ expires_at: new Date(Date.now() - 5_000).toISOString(),+ });+ render(+ <CredentialCard+ frame={frame}+ mode="inline-pause"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ const connect = screen.getByRole("button", { name: "Connect credential" });+ connect.focus();+ expect(document.activeElement).not.toBe(connect);+ });+});++describe("CredentialCard countdown (inline-pause vs terminal)", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("never renders a countdown in terminal mode, even with a future expiry", () => {+ const frame = buildCredentialRequiredFrame({+ expires_at: new Date(Date.now() + 300_000).toISOString(),+ });+ render(+ <CredentialCard+ frame={frame}+ mode="terminal"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(screen.queryByText(/^\d+:\d{2}$/)).toBeNull();+ act(() => {+ vi.advanceTimersByTime(600_000);+ });+ expect(screen.queryByText("Timed out")).toBeNull();+ expect(+ screen+ .getByRole("button", { name: "Connect credential" })+ .hasAttribute("disabled"),+ ).toBe(false);+ });++ it("ticks a countdown down in inline-pause mode", () => {+ const frame = buildCredentialRequiredFrame({+ expires_at: new Date(Date.now() + 300_000).toISOString(),+ });+ render(+ <CredentialCard+ frame={frame}+ mode="inline-pause"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(screen.getByText("5:00")).toBeTruthy();+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(screen.getByText("4:00")).toBeTruthy();+ });++ it("keeps the visible per-second countdown out of the aria-live region", () => {+ const frame = buildCredentialRequiredFrame({+ expires_at: new Date(Date.now() + 300_000).toISOString(),+ });+ render(+ <CredentialCard+ frame={frame}+ mode="inline-pause"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ const visible = screen.getByText("5:00");+ expect(visible.getAttribute("aria-live")).toBeNull();+ // Hidden from assistive tech so it doesn't get read twice alongside the+ // sr-only announcement below.+ expect(visible.getAttribute("aria-hidden")).toBe("true");+ });++ it("announces the countdown sparsely (once a minute, not every second)", () => {+ const frame = buildCredentialRequiredFrame({+ expires_at: new Date(Date.now() + 330_000).toISOString(),+ });+ render(+ <CredentialCard+ frame={frame}+ mode="inline-pause"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ const announcement = screen.getByText("5 minutes left to connect");+ expect(announcement.getAttribute("aria-live")).toBe("polite");++ // Ticking within the same minute must not change the announced text —+ // that's what would spam a screen reader every second. 330s -> 310s is+ // still inside the "5 minutes" bucket (floor(310/60) === 5).+ act(() => {+ vi.advanceTimersByTime(20_000);+ });+ expect(screen.getByText("5 minutes left to connect")).toBeTruthy();++ // Crossing the 300s/5:00 boundary is the only thing allowed to change it.+ act(() => {+ vi.advanceTimersByTime(20_000);+ });+ expect(screen.getByText("4 minutes left to connect")).toBeTruthy();+ });++ it("keeps the visible countdown and the sr-only announcement in agreement at the minute boundary", () => {+ // Regression pin: formatCountdown and formatCountdownAnnouncement used+ // to disagree right at a whole-minute mark (visible "1:00" vs announced+ // "less than a minute").+ const frame = buildCredentialRequiredFrame({+ expires_at: new Date(Date.now() + 60_000).toISOString(),+ });+ render(+ <CredentialCard+ frame={frame}+ mode="inline-pause"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(screen.getByText("1:00")).toBeTruthy();+ expect(screen.getByText("1 minute left to connect")).toBeTruthy();+ expect(screen.queryByText("Less than a minute left to connect")).toBeNull();+ });++ it("disables every control once the countdown expires, and disabled controls stay inert", () => {+ const onConnect = vi.fn();+ const onSkip = vi.fn();+ const frame = buildCredentialRequiredFrame({+ expires_at: new Date(Date.now() + 300_000).toISOString(),+ });+ render(+ <CredentialCard+ frame={frame}+ mode="inline-pause"+ matchingCredentials={ONE_MATCHING_CREDENTIAL}+ onConnect={onConnect}+ onSkip={onSkip}+ />,+ );+ act(() => {+ vi.advanceTimersByTime(300_000);+ });+ expect(screen.getAllByText("Timed out").length).toBeGreaterThan(0);++ 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();+ });++ it("stops the countdown interval once expired instead of ticking forever", () => {+ const frame = buildCredentialRequiredFrame({+ expires_at: new Date(Date.now() + 300_000).toISOString(),+ });+ render(+ <CredentialCard+ frame={frame}+ mode="inline-pause"+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ act(() => {+ vi.advanceTimersByTime(300_000);+ });+ expect(screen.getAllByText("Timed out").length).toBeGreaterThan(0);+ // The interval is the only timer this hook schedules; once it self-clears+ // on expiry, nothing should remain pending.+ expect(vi.getTimerCount()).toBe(0);+ });++ it("treats an unparseable expires_at as already expired instead of showing NaN:NaN", () => {+ const onConnect = vi.fn();+ const frame = buildCredentialRequiredFrame({ expires_at: "not-a-date" });+ render(+ <CredentialCard+ frame={frame}+ mode="inline-pause"+ onConnect={onConnect}+ onSkip={vi.fn()}+ />,+ );+ expect(screen.getAllByText("Timed out").length).toBeGreaterThan(0);+ expect(screen.queryByText(/NaN/)).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Connect credential" }));+ expect(onConnect).not.toHaveBeenCalled();+ });+});++describe("CredentialCard historical (resolvedOutcome) rendering", () => {+ it("renders a fallback instead of crashing on an out-of-union outcome value", () => {+ // Simulates untyped network data reaching a compile-time-exhaustive+ // switch — the type cast is the point of the test.+ const outOfBandOutcome = {+ outcome: "archived",+ } as unknown as CredentialPauseHistorical;+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ resolvedOutcome={outOfBandOutcome}+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(screen.getByText("Credential status unavailable")).toBeTruthy();+ });++ it("renders a named receipt for a connected outcome and fires no callbacks on mount", () => {+ const onConnect = vi.fn();+ const onSkip = vi.fn();+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ matchingCredentials={ONE_MATCHING_CREDENTIAL}+ resolvedOutcome={RESOLVED_OUTCOME_CONNECTED}+ onConnect={onConnect}+ onSkip={onSkip}+ />,+ );+ expect(screen.getByText("Credential 'HN login' added")).toBeTruthy();+ expect(+ screen.queryByRole("button", { name: "Connect credential" }),+ ).toBeNull();+ expect(onConnect).not.toHaveBeenCalled();+ expect(onSkip).not.toHaveBeenCalled();+ });++ it("falls back to unnamed receipt copy when the connected id has no matching credential", () => {+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ matchingCredentials={NO_MATCHING_CREDENTIALS}+ resolvedOutcome={RESOLVED_OUTCOME_CONNECTED}+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(screen.getByText("Credential added")).toBeTruthy();+ });++ it("renders the muted skip row for a skipped outcome", () => {+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="terminal"+ resolvedOutcome={RESOLVED_OUTCOME_SKIPPED}+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(+ screen.getByText(+ "Credential setup skipped — test run may stop at the login step",+ ),+ ).toBeTruthy();+ });++ it("renders the muted timeout row for a timeout outcome", () => {+ render(+ <CredentialCard+ frame={buildCredentialRequiredFrame()}+ mode="inline-pause"+ resolvedOutcome={RESOLVED_OUTCOME_TIMEOUT}+ onConnect={vi.fn()}+ onSkip={vi.fn()}+ />,+ );+ expect(+ screen.getByText(+ "Credential request timed out — test run may stop at the login step",+ ),+ ).toBeTruthy();+ });+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsxnew file mode 100644index 000000000..e2f68cf24--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx@@ -0,0 +1,322 @@+import { useEffect, useState } from "react";+import { Cross2Icon, LockClosedIcon } from "@radix-ui/react-icons";++import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";++// 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+// path yet. `type`/`reason` are the only fields a minimal signal guarantees;+// everything else on the frame below is populated only by a richer,+// timed pause signal and stays undefined otherwise.+export type CredentialRequiredReason =+ | "workflow_credential_inputs_unbound"+ | "credential_name_unresolved"+ | "credential_invention_requested"+ | "raw_secret"+ | "credential_deferred_draft"+ | "assistant_directed"+ | "missing_credential_run_failure";++export interface CredentialRequiredFrame {+ type: "credential_required";+ reason: CredentialRequiredReason;+ turn_id?: string;+ workflow_copilot_chat_id?: string;+ // Dynamic ask text; only a richer, timed signal supplies one today.+ message?: string;+ login_page_urls?: string[];+ credential_refs?: string[];+ timeout_seconds?: number;+ expires_at?: string;+ timestamp?: string;+}++export type CredentialCardMode = "terminal" | "inline-pause";++export type CredentialPauseOutcome = "connected" | "skipped" | "timeout";++export interface CredentialPauseHistorical {+ outcome: CredentialPauseOutcome;+ credentialId?: string;+}++export interface MatchingCredential {+ credentialId: string;+ name: 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;+ onSkip: () => void;+}++const SIGN_IN_WHY_LINE =+ "So it can sign in on your behalf when this workflow runs — stored encrypted, never shown in chat.";++// Exported for reuse elsewhere instead of re-deriving reason copy.+// eslint-disable-next-line react-refresh/only-export-components+export const CREDENTIAL_WHY_LINE_BY_REASON: Record<+ CredentialRequiredReason,+ string+> = {+ workflow_credential_inputs_unbound: SIGN_IN_WHY_LINE,+ // Lower-confidence text-marker detection of the same underlying need.+ assistant_directed: SIGN_IN_WHY_LINE,+ credential_name_unresolved:+ "I couldn't tell which saved credential you meant — connect or pick the right one so the workflow can sign in.",+ credential_invention_requested:+ "I can't invent login details — connect a real credential so the workflow can sign in safely.",+ raw_secret:+ "Don't paste secrets directly in chat — connect a credential so it's stored encrypted instead.",+ missing_credential_run_failure:+ "The last run stopped here because no credential was available — connect one so it can sign in automatically next time.",+ credential_deferred_draft:+ "You held off on this earlier — connect a credential now so the workflow can sign in when it runs.",+};++const SKIP_COPY =+ "Credential setup skipped — test run may stop at the login step";+const TIMEOUT_COPY =+ "Credential request timed out — test run may stop at the login step";++function siteFromLoginPageUrls(urls: string[] | undefined): string {+ const first = urls?.[0];+ if (!first) {+ return "the site";+ }+ try {+ return new URL(first).hostname;+ } catch {+ return first;+ }+}++function formatCountdown(remainingMs: number): string {+ const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ return `${minutes}:${String(seconds).padStart(2, "0")}`;+}++// A minute-rounded phrase for the screen-reader announcement: its text only+// changes once a minute, so aria-live fires once a minute, not every second.+// Derives minutes the same way formatCountdown does (floor of whole seconds)+// so the two can never disagree at a minute boundary.+function formatCountdownAnnouncement(remainingMs: number): string {+ const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));+ const minutes = Math.floor(totalSeconds / 60);+ if (minutes < 1) {+ return "Less than a minute left to connect";+ }+ return minutes === 1+ ? "1 minute left to connect"+ : `${minutes} minutes left to connect`;+}++// A missing OR malformed expires_at both fail safe as already-expired rather+// than leaving the card permanently enabled with a "NaN:NaN" countdown. This+// intentionally has no separate loading state: entering inline-pause mode+// before expires_at is populated renders "Timed out" rather than a spinner.+function computeRemainingMs(expiresAt: string): number {+ const ms = Date.parse(expiresAt) - Date.now();+ return Number.isNaN(ms) ? 0 : ms;+}++function useCountdown(expiresAt: string, active: boolean) {+ const [remainingMs, setRemainingMs] = useState(() =>+ computeRemainingMs(expiresAt),+ );++ useEffect(() => {+ if (!active) {+ return;+ }+ setRemainingMs(computeRemainingMs(expiresAt));+ const id = setInterval(() => {+ const next = computeRemainingMs(expiresAt);+ setRemainingMs(next);+ // Stop ticking once expired instead of re-rendering every second forever.+ if (next <= 0) {+ clearInterval(id);+ }+ }, 1000);+ return () => clearInterval(id);+ }, [expiresAt, active]);++ return { remainingMs, expired: remainingMs <= 0 };+}++function CredentialSystemRow({ text }: { text: string }) {+ return (+ <div className="flex items-center gap-2 px-1 py-1 text-xs text-muted-foreground">+ <span className="h-1 w-1 flex-none rounded-full bg-slate-600" />+ {text}+ </div>+ );+}++export function CredentialCard({+ frame,+ mode,+ matchingCredentials = [],+ resolvedOutcome,+ onConnect,+ onSkip,+}: 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+ // richer, timed pause signal has real expiry data, hence gating disablement+ // on inline-pause exclusively.+ const countdownActive = mode === "inline-pause" && !resolvedOutcome;+ const { remainingMs, expired } = useCountdown(+ frame.expires_at ?? "",+ countdownActive,+ );+ const disabled = countdownActive && expired;++ if (resolvedOutcome) {+ switch (resolvedOutcome.outcome) {+ case "skipped":+ return <CredentialSystemRow text={SKIP_COPY} />;+ case "timeout":+ return <CredentialSystemRow text={TIMEOUT_COPY} />;+ case "connected": {+ const name = matchingCredentials.find(+ (credential) =>+ credential.credentialId === resolvedOutcome.credentialId,+ )?.name;+ return (+ <div className="rounded-lg border border-border bg-slate-elevation2 p-3">+ <div className="flex items-center gap-2 text-xs font-semibold text-foreground">+ <span className="text-success">✓</span>+ {name ? `Credential '${name}' added` : "Credential added"}+ </div>+ <p className="mt-1 text-xs text-muted-foreground">+ Stored encrypted · used to sign in on your behalf · never enters+ the chat+ </p>+ </div>+ );+ }+ default: {+ // Compile-time exhaustiveness guard: a future CredentialPauseOutcome+ // value fails to typecheck here. Renders a fallback instead of+ // throwing since `resolvedOutcome` will eventually come off the+ // network, where a crash would take down the whole chat pane.+ const _exhaustive: never = resolvedOutcome.outcome;+ void _exhaustive;+ return <CredentialSystemRow text="Credential status unavailable" />;+ }+ }+ }++ const site = siteFromLoginPageUrls(frame.login_page_urls);+ const singleMatch =+ matchingCredentials.length === 1 ? matchingCredentials[0] : null;+ const multipleMatches = matchingCredentials.length >= 2;++ return (+ <div>+ {frame.message ? (+ <p className="text-sm leading-relaxed text-foreground">+ {frame.message}+ </p>+ ) : null}+ <div+ className={`rounded-lg border border-border bg-slate-elevation2 p-3 ${frame.message ? "mt-2" : ""}`}+ >+ <div className="flex items-start gap-2">+ <span className="flex h-5 w-5 flex-none items-center justify-center rounded-md bg-warning/10 text-warning">+ <LockClosedIcon className="h-3 w-3" />+ </span>+ <div className="min-w-0 flex-1">+ <div className="text-xs font-semibold text-foreground">+ Copilot needs to sign in to {site}+ </div>+ <p className="mt-0.5 text-[11px] leading-relaxed text-muted-foreground">+ {CREDENTIAL_WHY_LINE_BY_REASON[frame.reason] ?? SIGN_IN_WHY_LINE}+ </p>+ </div>+ {countdownActive ? (+ <>+ <span+ aria-hidden="true"+ className="flex-none text-[11px] tabular-nums text-muted-foreground"+ >+ {expired ? "Timed out" : formatCountdown(remainingMs)}+ </span>+ {/* Separate from the visible per-second display: this text only+ changes once a minute, so screen readers aren't spammed. */}+ <span className="sr-only" aria-live="polite">+ {expired+ ? "Timed out"+ : formatCountdownAnnouncement(remainingMs)}+ </span>+ </>+ ) : null}+ <button+ type="button"+ aria-label="Skip for now"+ onClick={() => onSkip()}+ disabled={disabled}+ className="flex h-5 w-5 flex-none items-center justify-center rounded-md text-slate-500 hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50"+ >+ <Cross2Icon className="h-3 w-3" />+ </button>+ </div>+ <div className="ml-7 mt-2.5 flex flex-wrap items-center gap-2">+ <button+ type="button"+ disabled={disabled}+ onClick={() => onConnect(undefined)}+ className="rounded-md bg-cta px-3 py-1 text-xs font-medium text-cta-foreground hover:bg-cta-hover disabled:pointer-events-none disabled:opacity-50"+ >+ Connect credential+ </button>+ {singleMatch ? (+ <button+ type="button"+ 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>+ ) : null}+ </div>+ </div>+ </div>+ );+}