Skip to content

Automate browser based workflows with AI

Let users sign in themselves from the Copilot credential card (SKY-17622) (#8776)

Andrew Neilson8308cc2f8905
diff --git a/skyvern-frontend/src/components/BrowserStream.tsx b/skyvern-frontend/src/components/BrowserStream.tsx
index 10e7332f8..ffdff0ac4 100644
--- a/skyvern-frontend/src/components/BrowserStream.tsx
+++ b/skyvern-frontend/src/components/BrowserStream.tsx
@@ -23,6 +23,7 @@ import { useLogging } from "@/hooks/useLogging";
import { statusIsNotFinalized } from "@/routes/tasks/types";
import { useRecordingStore } from "@/store/useRecordingStore";
import { useSettingsStore } from "@/store/SettingsStore";
+import { useManualSignInControl } from "@/store/useManualSignInStore";
import { wssBaseUrl, newWssBaseUrl } from "@/util/env";
import { installNoVncGestureCrashGuard } from "@/util/novncGestureCrashGuard";
import { cn } from "@/util/utils";
@@ -241,6 +242,10 @@ function BrowserStream({
parentSessionState?.isBrowserSessionEnded ?? polledIsBrowserSessionEnded;
const [hasGivenUp, setHasGivenUp] = useState(false);
const [userIsControlling, setUserIsControlling] = useState(false);
+ useManualSignInControl(
+ showControlButtons ? browserSessionId : undefined,
+ setUserIsControlling,
+ );
const [vncDisconnectedTrigger, setVncDisconnectedTrigger] = useState(0);
const [isVncConnected, setIsVncConnected] = useState<boolean>(false);
// The message socket must open after VNC's handshake has set the ALB
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
index 4df8f34d9..e4b134e4b 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
@@ -9,6 +9,7 @@ import {
} from "@/routes/streaming/useRecordingMessageChannel";
import { toast } from "@/components/ui/use-toast";
import { InteractiveStreamView } from "@/routes/streaming/InteractiveStreamView";
+import { useManualSignInControl } from "@/store/useManualSignInStore";
import {
toastClipboardReadFailed,
toastNothingToPaste,
@@ -301,6 +302,10 @@ function BrowserSessionStream({
// Recording keeps copy local so the keystroke never lands in the capture.
forwardCopyShortcut: !exfiltrate,
});
+ useManualSignInControl(
+ controllable ? browserSessionId : undefined,
+ setUserIsControlling,
+ );
const keepMessageChannelAlive = !!exfiltrate || userIsControlling;
keepMessageChannelAliveRef.current = keepMessageChannelAlive;
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 647a73e20..c1e848b73 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -70,6 +70,7 @@ import {
} from "@/store/WorkflowHasChangesStore";
import { useWorkflowTitleStore } from "@/store/WorkflowTitleStore";
import { useCopilotActionStore } from "@/store/useCopilotActionStore";
+import { useManualSignInStore } from "@/store/useManualSignInStore";
import {
type CopilotAttention,
useCopilotHeaderStore,
@@ -122,6 +123,7 @@ import {
WorkflowCopilotWorkflowDraftUpdate,
WorkflowCopilotCodegenProgressUpdate,
WorkflowCopilotCredentialRequiredUpdate,
+ WorkflowCopilotCredentialResponseResult,
WorkflowCopilotCredentialPauseResolvedUpdate,
WorkflowCopilotTitleUpdate,
WorkflowCopilotChatSender,
@@ -226,7 +228,10 @@ import { useSpeechToTextField } from "@/hooks/useSpeechToTextField";
import { SpeechInputButton } from "@/components/SpeechInputButton";
import { cn, formatElapsedSeconds } from "@/util/utils";
import { ControlTooltip } from "@/routes/workflows/studio/ControlTooltip";
-import { useSwitchStudioRun } from "@/routes/workflows/studio/runSwitchNavigation";
+import {
+ searchWithoutRun,
+ useSwitchStudioRun,
+} from "@/routes/workflows/studio/runSwitchNavigation";
import { searchWithSystemBlockFocus } from "@/routes/workflows/editor/hooks/useSelectedBlockUrlSync";
import { studioPanelId } from "@/routes/workflows/studio/constants";
import {
@@ -1895,6 +1900,13 @@ export function WorkflowCopilotChat({
const [pauseCardResolutions, setPauseCardResolutions] = useState<
Record<string, CredentialResolution>
>({});
+ // Per resume token: a Done in flight, the site a Done found no sign-in for, or a Done that failed to save.
+ const [manualSignIns, setManualSignIns] = useState<
+ Record<
+ string,
+ { busy: boolean; notFoundHost?: string; saveFailed?: boolean }
+ >
+ >({});
// 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.
@@ -2539,10 +2551,10 @@ export function WorkflowCopilotChat({
const respondToCredentialPause = useCallback(
async (
frame: WorkflowCopilotCredentialRequiredUpdate,
- action: "connected" | "skip",
+ action: "connected" | "skip" | "signing_in" | "signed_in",
credentialId?: string,
name?: string,
- ) => {
+ ): Promise<WorkflowCopilotCredentialResponseResult | undefined> => {
if (credentialResponseInFlight.current) return;
if (
!streamingAbortController.current &&
@@ -2561,13 +2573,22 @@ export function WorkflowCopilotChat({
// Copilot routes live on base_router (no /api/v1 prefix), like cancel.
const client = await getClient(credentialGetter, "sans-api-v1");
if (!isCopilotTurnCurrent(reservation)) return;
- await client.post("/workflow/copilot/credential-response", {
- turn_id: frame.turn_id,
- workflow_copilot_chat_id: frame.workflow_copilot_chat_id,
- resume_token: frame.resume_token,
- action,
- credential_id: action === "connected" ? credentialId : undefined,
- });
+ const response =
+ await client.post<WorkflowCopilotCredentialResponseResult>(
+ "/workflow/copilot/credential-response",
+ {
+ turn_id: frame.turn_id,
+ workflow_copilot_chat_id: frame.workflow_copilot_chat_id,
+ resume_token: frame.resume_token,
+ action,
+ credential_id: action === "connected" ? credentialId : undefined,
+ },
+ );
+ // A backend that predates sign-in answers 204 with no body.
+ const result: WorkflowCopilotCredentialResponseResult = response.data
+ ?.result
+ ? response.data
+ : { result: "accepted" };
if (
!isCopilotTurnCurrent(reservation) ||
recoveryGeneration.current !== generation ||
@@ -2583,10 +2604,19 @@ export function WorkflowCopilotChat({
frame.turn_id,
);
}
+ if (
+ action === "signing_in" ||
+ result.result === "no_sign_in_found" ||
+ result.result === "save_failed"
+ ) {
+ return result;
+ }
const resolution: CredentialResolution =
action === "connected"
? { outcome: "connected", credentialId, name }
- : { outcome: "skipped" };
+ : action === "signed_in"
+ ? { outcome: "signed_in" }
+ : { outcome: "skipped" };
// The waiter's credential_pause_resolved frame can land first and carries the admitted verdict.
setPauseCardResolutions((prev) =>
prev[frame.resume_token]
@@ -2599,6 +2629,7 @@ export function WorkflowCopilotChat({
withCappedResolution(prev, frame.turn_id, resolution),
);
}
+ return result;
} catch (error) {
if (!isCopilotTurnCurrent(reservation)) return;
// Log only the message: the AxiosError serializes config.data, which
@@ -2623,6 +2654,48 @@ export function WorkflowCopilotChat({
},
[credentialGetter, isCopilotTurnCurrent, logCopilotRequestFailure],
);
+ const startManualSignIn = useCallback(
+ async (frame: WorkflowCopilotCredentialRequiredUpdate) => {
+ const result = await respondToCredentialPause(frame, "signing_in");
+ if (!result) return;
+ // The card's countdown, its place in the open asks, and a reload all read the frame.
+ const startSignIn = (
+ candidate: WorkflowCopilotCredentialRequiredUpdate,
+ ) =>
+ candidate.resume_token === frame.resume_token
+ ? {
+ ...candidate,
+ signing_in: true,
+ expires_at: result.expires_at ?? candidate.expires_at,
+ }
+ : candidate;
+ setLivePauseFrame((prev) => (prev ? startSignIn(prev) : prev));
+ setRecoveredPauseFrames((prev) => prev.map(startSignIn));
+ },
+ [respondToCredentialPause],
+ );
+ const finishManualSignIn = useCallback(
+ async (frame: WorkflowCopilotCredentialRequiredUpdate) => {
+ const token = frame.resume_token;
+ setManualSignIns((prev) => ({
+ ...prev,
+ [token]: { ...prev[token], busy: true },
+ }));
+ const result = await respondToCredentialPause(frame, "signed_in");
+ setManualSignIns((prev) => ({
+ ...prev,
+ [token]: {
+ busy: false,
+ notFoundHost:
+ result?.result === "no_sign_in_found"
+ ? (result.host ?? undefined)
+ : undefined,
+ saveFailed: result?.result === "save_failed",
+ },
+ }));
+ },
+ [respondToCredentialPause],
+ );
// Terminal-mode cards have no resume_token — connect/skip is a local UI morph,
// no network call.
const resolveTerminalCredential = useCallback(
@@ -6806,6 +6879,48 @@ export function WorkflowCopilotChat({
Date.parse(frame.expires_at ?? "") > Date.now(),
);
const trayPauseFrame = openPauseFrames[0] ?? null;
+ const signingInSessionId =
+ openPauseFrames.find(
+ (frame) =>
+ frame.signing_in &&
+ // Done hands the browser back before its cookies are read.
+ !manualSignIns[frame.resume_token]?.busy &&
+ frame.sign_in_browser_session_id === (liveBrowserSessionId ?? null),
+ )?.sign_in_browser_session_id ?? null;
+ const setManualSignInSession = useManualSignInStore(
+ (state) => state.setBrowserSessionId,
+ );
+ useEffect(() => {
+ setManualSignInSession(signingInSessionId);
+ }, [signingInSessionId, setManualSignInSession]);
+ // The sign-in happens in the live browser, so a pane showing a past run goes back to it, once per sign-in.
+ const signInShownSessionId = useRef<string | null>(null);
+ useEffect(() => {
+ if (signingInSessionId === signInShownSessionId.current) return;
+ signInShownSessionId.current = signingInSessionId;
+ if (!signingInSessionId) return;
+ const search = liveSearch(location.search);
+ if (!new URLSearchParams(search).has("wr")) return;
+ navigate(
+ {
+ pathname: location.pathname,
+ search: searchWithoutRun(search),
+ hash: location.hash,
+ },
+ {
+ replace: true,
+ state: liveLocationState(location.search, location.state),
+ },
+ );
+ }, [
+ signingInSessionId,
+ navigate,
+ location.pathname,
+ location.search,
+ location.hash,
+ location.state,
+ ]);
+ useEffect(() => () => setManualSignInSession(null), [setManualSignInSession]);
const nextPauseExpiry = openPauseFrames.length
? Math.min(
...openPauseFrames.map((frame) => Date.parse(frame.expires_at ?? "")),
@@ -9347,6 +9462,20 @@ export function WorkflowCopilotChat({
: openCredentialModal(frame, frame.turn_id)
}
onSkip={() => void respondToCredentialPause(frame, "skip")}
+ signIn={
+ frame.sign_in_browser_session_id &&
+ frame.sign_in_browser_session_id === liveBrowserSessionId
+ ? {
+ busy: Boolean(manualSignIns[frame.resume_token]?.busy),
+ notFoundHost: manualSignIns[frame.resume_token]?.notFoundHost,
+ saveFailed: Boolean(
+ manualSignIns[frame.resume_token]?.saveFailed,
+ ),
+ onStart: () => void startManualSignIn(frame),
+ onDone: () => void finishManualSignIn(frame),
+ }
+ : undefined
+ }
tray={tray}
/>
);
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx
index 93c5832c3..802c1b3a0 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.test.tsx
@@ -26,6 +26,7 @@ import {
CredentialCard,
type CredentialPauseHistorical,
type CredentialRequiredReason,
+ type ManualSignInOffer,
} from "./CredentialCard";
const { getClientMock, credsData, credsFail, clientGet } = vi.hoisted(() => {
@@ -335,6 +336,99 @@ describe("CredentialCard callbacks", () => {
});
});
+describe("CredentialCard sign in myself", () => {
+ const signIn = (overrides: Partial<ManualSignInOffer> = {}) => ({
+ busy: false,
+ onStart: vi.fn(),
+ onDone: vi.fn(),
+ ...overrides,
+ });
+
+ it("offers signing in yourself only when the chat passes an offer", () => {
+ const offer = signIn();
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ signIn={offer}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Sign in myself" }));
+ expect(offer.onStart).toHaveBeenCalledTimes(1);
+ cleanup();
+
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(screen.queryByRole("button", { name: "Sign in myself" })).toBeNull();
+ });
+
+ it("while signing in, Done finishes, Cancel skips, and a Done that found nothing says so", () => {
+ const offer = signIn({ notFoundHost: "portal.example.com" });
+ const onSkip = vi.fn();
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame({ signing_in: true })}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={onSkip}
+ signIn={offer}
+ />,
+ );
+ expect(
+ screen.getAllByText(/No sign-in found for portal\.example\.com/),
+ ).not.toHaveLength(0);
+ fireEvent.click(screen.getByRole("button", { name: "Done" }));
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(offer.onDone).toHaveBeenCalledTimes(1);
+ expect(onSkip).toHaveBeenCalledTimes(1);
+ expect(
+ screen.getByRole("button", { name: "Connect credential" }),
+ ).toBeTruthy();
+ });
+
+ it("says when a Done could not save the sign-in, not that none was found", () => {
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame({ signing_in: true })}
+ mode="inline-pause"
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ signIn={signIn({
+ saveFailed: true,
+ notFoundHost: "portal.example.com",
+ })}
+ />,
+ );
+ expect(screen.getAllByText(/Couldn't save your sign-in/)).not.toHaveLength(
+ 0,
+ );
+ expect(screen.queryByText(/No sign-in found/)).toBeNull();
+ });
+
+ it("renders a signed-in receipt naming the saved profile", () => {
+ render(
+ <CredentialCard
+ frame={buildCredentialRequiredFrame()}
+ mode="inline-pause"
+ resolvedOutcome={{ outcome: "signed_in", name: "Sign-in for portal" }}
+ onConnect={vi.fn()}
+ onSkip={vi.fn()}
+ />,
+ );
+ expect(
+ screen.getByText("Signed in, saved as 'Sign-in for portal'"),
+ ).toBeTruthy();
+ });
+});
+
describe("CredentialCard terminal org-credential picker", () => {
it("fetches the org credentials and renders them as a picker, in API order", async () => {
credsData.current = [
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx
index 2c8d1c749..be8e194c4 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/CredentialCard.tsx
@@ -74,12 +74,17 @@ export interface CredentialRequiredFrame {
credential_refs?: string[];
timeout_seconds?: number;
expires_at?: string;
+ signing_in?: boolean;
timestamp?: string;
}
export type CredentialCardMode = "terminal" | "inline-pause" | "auto-bound";
-export type CredentialPauseOutcome = "connected" | "skipped" | "timeout";
+export type CredentialPauseOutcome =
+ | "connected"
+ | "skipped"
+ | "timeout"
+ | "signed_in";
export interface CredentialPauseHistorical {
outcome: CredentialPauseOutcome;
@@ -128,6 +133,18 @@ export interface CredentialCardProps {
canChange?: boolean;
// Set when the chat docks this ask above the composer instead of in the transcript.
tray?: AttentionTrayPresentation;
+ // Offered only when the card's browser is the one on screen, so the user signs in where the agent looks.
+ signIn?: ManualSignInOffer;
+}
+
+export interface ManualSignInOffer {
+ busy: boolean;
+ // Set after a Done that found no sign-in cookies for the site.
+ notFoundHost?: string;
+ // Set after a Done whose sign-in could not be read or saved.
+ saveFailed?: boolean;
+ onStart: () => void;
+ onDone: () => void;
}
const SIGN_IN_WHY_LINE =
@@ -191,6 +208,8 @@ const UPDATE_SKIP_OUTCOME = {
meta: "keeps its saved sign-in",
detail: "Credential not updated — the workflow keeps its saved sign-in.",
};
+const SIGNED_IN_DETAIL =
+ "No password stored · your sign-in is saved as browser cookies in this profile";
const TIMEOUT_OUTCOME = {
title: "Sign-in request timed out",
meta: "test may stop at login",
@@ -754,6 +773,7 @@ function CredentialAskCard({
autoBound,
canChange = false,
tray,
+ signIn,
}: 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
@@ -906,6 +926,18 @@ function CredentialAskCard({
);
case "timeout":
return <ResolvedCredentialCard tone="warn" {...TIMEOUT_OUTCOME} />;
+ case "signed_in":
+ return (
+ <ResolvedCredentialCard
+ tone="done"
+ title={
+ resolvedOutcome.name
+ ? `Signed in, saved as '${resolvedOutcome.name}'`
+ : "Signed in, saved as a browser profile"
+ }
+ detail={SIGNED_IN_DETAIL}
+ />
+ );
case "connected": {
const name = resolvedOutcome.name;
// A save from the editor does not prove 2FA was added; the retried step says whether it was.
@@ -1017,6 +1049,85 @@ function CredentialAskCard({
}
const site = siteFromLoginPageUrls(frame.login_page_urls);
+ const connectButton = (
+ <Button
+ type="button"
+ size="sm"
+ variant={signIn && frame.signing_in ? "outline" : "default"}
+ disabled={disabled}
+ onClick={() => onConnect(undefined)}
+ data-tour="credential-connect"
+ >
+ Connect credential
+ </Button>
+ );
+ if (signIn && frame.signing_in) {
+ const notFound = signIn.saveFailed
+ ? "Couldn't save your sign-in. Click Done to try again, or connect a credential."
+ : signIn.notFoundHost
+ ? `No sign-in found for ${signIn.notFoundHost}. Sign in, then click Done again.`
+ : "";
+ return (
+ <AskChrome
+ tray={tray}
+ rootRef={rootRef}
+ message={frame.message}
+ title={`Sign in to ${site} in the browser`}
+ countdown={
+ <PauseCountdown remainingMs={remainingMs} expired={expired} />
+ }
+ lines={[
+ <span
+ key="how"
+ className="text-[11px] leading-relaxed text-muted-foreground"
+ >
+ Use the browser to sign in, including any verification code, then
+ click Done. Skyvern saves the sign-in as a browser profile; no
+ password is stored.
+ </span>,
+ ...(notFound
+ ? [
+ <span key="not-found" className="text-[11px] font-medium">
+ {notFound}
+ </span>,
+ ]
+ : []),
+ ]}
+ footer={
+ <>
+ <Button
+ type="button"
+ size="sm"
+ disabled={disabled || signIn.busy}
+ onClick={signIn.onDone}
+ >
+ {signIn.busy ? "Saving sign-in…" : "Done"}
+ </Button>
+ {connectButton}
+ <div className="ml-auto">
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => onSkip()}
+ disabled={disabled || signIn.busy}
+ >
+ Cancel
+ </Button>
+ </div>
+ </>
+ }
+ announcer={
+ <span
+ className="sr-only"
+ role={insideLiveRegion ? undefined : "status"}
+ >
+ {insideLiveRegion ? "" : notFound}
+ </span>
+ }
+ />
+ );
+ }
return (
<AskChrome
tray={tray}
@@ -1048,15 +1159,18 @@ function CredentialAskCard({
]}
footer={
<>
- <Button
- type="button"
- size="sm"
- disabled={disabled}
- onClick={() => onConnect(undefined)}
- data-tour="credential-connect"
- >
- Connect credential
- </Button>
+ {connectButton}
+ {signIn ? (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={disabled || signIn.busy}
+ onClick={signIn.onStart}
+ >
+ Sign in myself
+ </Button>
+ ) : null}
{orgCredentials.status === "ready" &&
(pickable.length > 0 || pickerEngaged) ? (
<CredentialPicker
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index 7976ac55a..d1cb734f4 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -437,7 +437,7 @@ export interface TurnNarrativeState {
// Resolved pause outcome, from the credentialPause narrative signal.
// "declined" means the pause engaged but never sent a frame, so no card.
credentialPause: {
- outcome: "connected" | "skipped" | "timeout" | "declined";
+ outcome: "connected" | "skipped" | "timeout" | "declined" | "signed_in";
credentialId: string | null;
// The tool call whose row was newest when the card was raised. Absent on
// turns recorded before it was stamped.
@@ -564,7 +564,8 @@ export function parseCredentialPause(
outcome !== "connected" &&
outcome !== "skipped" &&
outcome !== "timeout" &&
- outcome !== "declined"
+ outcome !== "declined" &&
+ outcome !== "signed_in"
) {
return null;
}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index 955c5117b..96df2f1a5 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -432,17 +432,28 @@ export interface WorkflowCopilotCredentialRequiredUpdate {
// The tool call whose activity row was newest when the pause was raised, so
// the card renders there. Absent against a backend that predates it.
anchor_tool_call_id?: string | null;
+ // The live browser the user may sign in to themselves; absent when the card does not offer it.
+ sign_in_browser_session_id?: string | null;
+ signing_in?: boolean;
timestamp: string;
}
+export interface WorkflowCopilotCredentialResponseResult {
+ result: "accepted" | "signed_in" | "no_sign_in_found" | "save_failed";
+ expires_at?: string | null;
+ host?: string | null;
+ browser_profile_id?: string | null;
+}
+
export interface WorkflowCopilotCredentialPauseResolvedUpdate {
type: "credential_pause_resolved";
turn_id: string;
workflow_copilot_chat_id: string;
resume_token: string;
- outcome: "connected" | "skipped" | "not_admitted";
+ outcome: "connected" | "skipped" | "not_admitted" | "signed_in";
credential_id: string | null;
name: string | null;
+ browser_profile_id?: string | null;
timestamp: string;
}
diff --git a/skyvern-frontend/src/routes/workflows/studio/runSwitchNavigation.test.ts b/skyvern-frontend/src/routes/workflows/studio/runSwitchNavigation.test.ts
index 8d9006c50..54096372d 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runSwitchNavigation.test.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/runSwitchNavigation.test.ts
@@ -4,6 +4,7 @@ import { MemoryRouter, Route, Routes } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
+ searchWithoutRun,
searchWithRunSwitched,
useSwitchStudioRun,
} from "./runSwitchNavigation";
@@ -42,6 +43,14 @@ beforeEach(() => {
navigate.mockClear();
});
+describe("searchWithoutRun", () => {
+ it("drops the inspected run and its selection but keeps the pane layout", () => {
+ expect(
+ searchWithoutRun("?panes=browser&wr=wr_1&wrs=copilot&active=b1&bl=x"),
+ ).toBe("?panes=browser");
+ });
+});
+
describe("searchWithRunSwitched system focus", () => {
it("marks a system focus, and a user switch takes the marker back off", () => {
const focused = searchWithRunSwitched("?panes=browser", "wr_1", {
diff --git a/skyvern-frontend/src/routes/workflows/studio/runSwitchNavigation.ts b/skyvern-frontend/src/routes/workflows/studio/runSwitchNavigation.ts
index eef207e1f..558d46794 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runSwitchNavigation.ts
+++ b/skyvern-frontend/src/routes/workflows/studio/runSwitchNavigation.ts
@@ -47,6 +47,21 @@ export function searchWithRunSwitched(
return toReadableSearch(params);
}
+// Point the studio back at its live browser: drop the inspected run and its per-run selection.
+export function searchWithoutRun(search: string): string {
+ const params = new URLSearchParams(search);
+ for (const key of [
+ "wr",
+ SYSTEM_RUN_FOCUS_PARAM,
+ "active",
+ "bl",
+ "iteration",
+ ]) {
+ params.delete(key);
+ }
+ return toReadableSearch(params);
+}
+
/**
* Switch the studio's inspected run from a user action (e.g. the Past Runs
* list). The single place run-switch navigation lives, so surfaces that touch
diff --git a/skyvern-frontend/src/store/useManualSignInStore.ts b/skyvern-frontend/src/store/useManualSignInStore.ts
new file mode 100644
index 000000000..02d7b2202
--- /dev/null
+++ b/skyvern-frontend/src/store/useManualSignInStore.ts
@@ -0,0 +1,32 @@
+import { useEffect, useRef } from "react";
+import { create } from "zustand";
+
+type ManualSignInStore = {
+ // The live browser the user is signing in to from a Copilot credential card, if any.
+ browserSessionId: string | null;
+ setBrowserSessionId: (browserSessionId: string | null) => void;
+};
+
+export const useManualSignInStore = create<ManualSignInStore>((set) => ({
+ browserSessionId: null,
+ setBrowserSessionId: (browserSessionId) => set({ browserSessionId }),
+}));
+
+// Hands the stream to the user while they sign in to this browser, and back when they finish.
+export function useManualSignInControl(
+ browserSessionId: string | undefined,
+ setUserIsControlling: (controlling: boolean) => void,
+) {
+ const signingIn = useManualSignInStore(
+ (state) =>
+ browserSessionId !== undefined &&
+ state.browserSessionId === browserSessionId,
+ );
+ const wasSigningIn = useRef(false);
+ useEffect(() => {
+ if (signingIn !== wasSigningIn.current) {
+ setUserIsControlling(signingIn);
+ }
+ wasSigningIn.current = signingIn;
+ }, [signingIn, setUserIsControlling]);
+}
diff --git a/skyvern/config.py b/skyvern/config.py
index d2467f354..e8f7e1e55 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -278,6 +278,8 @@ class Settings(BaseSettings):
# so this is a guaranteed no-op behind app.CACHE.is_shared regardless of this flag.
WORKFLOW_COPILOT_CREDENTIAL_PAUSE_ENABLED: bool = True
WORKFLOW_COPILOT_CREDENTIAL_PAUSE_TIMEOUT_SECONDS: int = 300
+ # Replaces the pause countdown once when the user chooses to sign in themselves in the live browser.
+ WORKFLOW_COPILOT_MANUAL_SIGN_IN_TIMEOUT_SECONDS: int = 900
# Kill switch for the live codegen-progress SSE frame (drafted block labels while an authoring
# tool call streams). Off restores exact pre-change behavior; old frontends drop the frame either way.
WORKFLOW_COPILOT_CODEGEN_PROGRESS_ENABLED: bool = True
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 5e53daa22..c99d56342 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -2166,6 +2166,11 @@ def _make_agent_result(
pause_payload = {"outcome": pause_outcome}
if pause_outcome == "connected" and ctx.credential_pause_connected_credential_id:
pause_payload["credentialId"] = ctx.credential_pause_connected_credential_id
+ signed_in_profile_id = (
+ ctx.request_policy.credential_pause_signed_in_profile_id if ctx.request_policy else None
+ )
+ if pause_outcome == "signed_in" and signed_in_profile_id:
+ pause_payload["browserProfileId"] = signed_in_profile_id
if ctx.credential_pause_anchor_tool_call_id:
pause_payload["anchorToolCallId"] = ctx.credential_pause_anchor_tool_call_id
payload_updates["credentialPause"] = pause_payload
diff --git a/skyvern/forge/sdk/copilot/credential_pause.py b/skyvern/forge/sdk/copilot/credential_pause.py
index 69ec5a54d..9fd847912 100644
--- a/skyvern/forge/sdk/copilot/credential_pause.py
+++ b/skyvern/forge/sdk/copilot/credential_pause.py
@@ -26,10 +26,11 @@ import re
import secrets
import time
from collections.abc import Awaitable, Callable
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from datetime import datetime, timedelta, timezone
from http import HTTPStatus
from typing import TYPE_CHECKING, Any, Literal, Protocol
+from urllib.parse import urlparse
import structlog
from pydantic import ValidationError
@@ -37,6 +38,7 @@ from pydantic import ValidationError
from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.sdk.browser_action_policy import canonicalize_origin
+from skyvern.forge.sdk.cache.base import BaseCache
from skyvern.forge.sdk.copilot.config import CopilotConfig
from skyvern.forge.sdk.copilot.credential_resolution import loggable_origin, safe_admitted_url, url_parts
from skyvern.forge.sdk.copilot.diagnosis_repair_contract import DiagnosisFailureType, RepairNextAction
@@ -82,10 +84,29 @@ def _credential_pause_lock_key(organization_id: str, chat_id: str, turn_id: str)
return f"copilot_credential_pause_lock:{organization_id}:{chat_id}:{turn_id}"
+# A Done claim reserves the pause while the profile is saved outside the lock; the save itself is bounded
+# tighter so the claim always outlives it.
+MANUAL_SIGN_IN_CLAIM_SECONDS = 120
+MANUAL_SIGN_IN_SAVE_TIMEOUT_SECONDS = 90
+
+
def _credential_pause_record_ttl(timeout_seconds: int) -> timedelta:
return timedelta(seconds=timeout_seconds + CREDENTIAL_PAUSE_RECORD_TTL_GRACE_SECONDS)
+def longest_credential_pause_seconds() -> int:
+ """A sign-in can start as the card's wait expires and then hold a Done claim, so all three add up."""
+ return (
+ settings.WORKFLOW_COPILOT_CREDENTIAL_PAUSE_TIMEOUT_SECONDS
+ + settings.WORKFLOW_COPILOT_MANUAL_SIGN_IN_TIMEOUT_SECONDS
+ + MANUAL_SIGN_IN_CLAIM_SECONDS
+ )
+
+
+def _longest_credential_pause_record_ttl() -> timedelta:
+ return _credential_pause_record_ttl(longest_credential_pause_seconds())
+
+
def _new_resume_token() -> str:
return secrets.token_urlsafe(32)
@@ -103,13 +124,58 @@ class CredentialPauseRejection(Exception):
self.detail = detail
+@dataclass
+class ManualSignIn:
+ """What a card that offers signing in yourself needs on Done, recorded server-side when the card is raised."""
+
+ browser_session_id: str
+ login_urls: list[str]
+ profile_name: str
+ started: bool = False
+
+
@dataclass
class _ActivePauseRecord:
resume_token: str
- status: Literal["pending", "consumed"]
+ status: Literal["pending", "resolving", "consumed"]
expires_at: datetime
card: WorkflowCopilotCredentialRequiredUpdate | None = None
recovery_token_digest: str | None = None
+ manual_sign_in: ManualSignIn | None = None
+ claim_id: str | None = None
+ claim_deadline: datetime | None = None
+
+ def live_until(self) -> datetime | None:
+ if self.status == "pending":
+ return self.expires_at
+ if self.status == "resolving":
+ return self.claim_deadline
+ return None
+
+
+def _encode_record(record: _ActivePauseRecord) -> str:
+ sign_in = record.manual_sign_in
+ return json.dumps(
+ {
+ "resume_token": record.resume_token,
+ "status": record.status,
+ "expires_at": record.expires_at.isoformat(),
+ "card": record.card.model_dump(mode="json") if record.card is not None else None,
+ "recovery_token_digest": record.recovery_token_digest,
+ "manual_sign_in": (
+ {
+ "browser_session_id": sign_in.browser_session_id,
+ "login_urls": sign_in.login_urls,
+ "profile_name": sign_in.profile_name,
+ "started": sign_in.started,
+ }
+ if sign_in is not None
+ else None
+ ),
+ "claim_id": record.claim_id,
+ "claim_deadline": record.claim_deadline.isoformat() if record.claim_deadline else None,
+ }
+ )
def _encode_active_pause(
@@ -119,18 +185,48 @@ def _encode_active_pause(
consumed: bool = False,
card: WorkflowCopilotCredentialRequiredUpdate | None = None,
recovery_token_digest: str | None = None,
+ manual_sign_in: ManualSignIn | None = None,
) -> str:
- return json.dumps(
- {
- "resume_token": resume_token,
- "status": "consumed" if consumed else "pending",
- "expires_at": expires_at.isoformat(),
- "card": card.model_dump(mode="json") if card is not None else None,
- "recovery_token_digest": recovery_token_digest,
- }
+ return _encode_record(
+ _ActivePauseRecord(
+ resume_token=resume_token,
+ status="consumed" if consumed else "pending",
+ expires_at=expires_at,
+ card=card,
+ recovery_token_digest=recovery_token_digest,
+ manual_sign_in=manual_sign_in,
+ )
+ )
+
+
+def _decode_manual_sign_in(data: Any) -> ManualSignIn | None:
+ if not isinstance(data, dict):
+ return None
+ session_id = data.get("browser_session_id")
+ login_urls = data.get("login_urls")
+ profile_name = data.get("profile_name")
+ if (
+ not isinstance(session_id, str)
+ or not isinstance(profile_name, str)
+ or not isinstance(login_urls, list)
+ or not all(isinstance(url, str) for url in login_urls)
+ ):
+ return None
+ return ManualSignIn(
+ browser_session_id=session_id,
+ login_urls=login_urls,
+ profile_name=profile_name,
+ started=data.get("started") is True,
)
+def _decode_datetime(raw: Any) -> datetime | None:
+ try:
+ return datetime.fromisoformat(raw) if isinstance(raw, str) else None
+ except ValueError:
+ return None
+
+
def _decode_active_pause(raw: Any) -> _ActivePauseRecord | None:
try:
data = json.loads(raw)
@@ -140,23 +236,26 @@ def _decode_active_pause(raw: Any) -> _ActivePauseRecord | None:
return None
token = data.get("resume_token")
record_status = data.get("status")
- if not isinstance(token, str) or record_status not in ("pending", "consumed"):
+ if not isinstance(token, str) or record_status not in ("pending", "resolving", "consumed"):
return None
- try:
- expires_at = datetime.fromisoformat(str(data.get("expires_at")))
- except ValueError:
+ expires_at = _decode_datetime(data.get("expires_at"))
+ if expires_at is None:
return None
try:
card = WorkflowCopilotCredentialRequiredUpdate.model_validate(data["card"]) if data.get("card") else None
except ValidationError:
card = None
digest = data.get("recovery_token_digest")
+ claim_id = data.get("claim_id")
return _ActivePauseRecord(
resume_token=token,
status=record_status,
expires_at=expires_at,
card=card,
recovery_token_digest=digest if isinstance(digest, str) else None,
+ manual_sign_in=_decode_manual_sign_in(data.get("manual_sign_in")),
+ claim_id=claim_id if isinstance(claim_id, str) else None,
+ claim_deadline=_decode_datetime(data.get("claim_deadline")),
)
@@ -241,10 +340,14 @@ async def pending_credential_requests(
or not secrets.compare_digest(digest, record.recovery_token_digest)
):
continue
- try:
- _validate_pending_pause(record, record.resume_token)
- except CredentialPauseRejection:
- continue
+ live_until = record.live_until()
+ # A Done being saved still owns the card: if it finds no sign-in, the pause reopens for this tab.
+ saving = record.status == "resolving" and live_until is not None and datetime.now(timezone.utc) < live_until
+ if not saving:
+ try:
+ _validate_pending_pause(record, record.resume_token)
+ except CredentialPauseRejection:
+ continue
card = record.card
if (
card.turn_id == turn_id
@@ -266,7 +369,8 @@ async def credential_pause_is_active(organization_id: str, chat_id: str, turn_id
except Exception:
LOG.warning("Failed to inspect Copilot credential pause", exc_info=True)
return None
- return bool(record is not None and record.status == "pending" and datetime.now(timezone.utc) < record.expires_at)
+ live_until = record.live_until() if record is not None else None
+ return bool(live_until is not None and datetime.now(timezone.utc) < live_until)
async def check_credential_pause_resumable(
@@ -321,24 +425,58 @@ async def resolve_credential_pause(
)
+@dataclass(frozen=True)
+class SignedInProfile:
+ browser_profile_id: str
+ profile_name: str
+ site: str
+ cookie_count: int
+
+
@dataclass
class CredentialPauseResolution:
- action: Literal["connected", "skip"]
+ action: Literal["connected", "skip", "signed_in"]
credential: Credential | None = None
+ signed_in: SignedInProfile | None = None
def encode_credential_response(
- action: Literal["connected", "skip"], credential_id: str | None, resume_token: str
+ action: Literal["connected", "skip", "signed_in"],
+ credential_id: str | None,
+ resume_token: str,
+ signed_in: SignedInProfile | None = None,
) -> str:
- return json.dumps({"action": action, "credential_id": credential_id, "resume_token": resume_token})
+ payload: dict[str, Any] = {"action": action, "credential_id": credential_id, "resume_token": resume_token}
+ if signed_in is not None:
+ payload["signed_in"] = {
+ "browser_profile_id": signed_in.browser_profile_id,
+ "profile_name": signed_in.profile_name,
+ "site": signed_in.site,
+ "cookie_count": signed_in.cookie_count,
+ }
+ return json.dumps(payload)
-def _decode_credential_response(raw: Any) -> tuple[str, str | None, str | None] | None:
+def _decode_signed_in(data: Any) -> SignedInProfile | None:
+ if not isinstance(data, dict):
+ return None
+ profile_id, name, site, count = (
+ data.get("browser_profile_id"),
+ data.get("profile_name"),
+ data.get("site"),
+ data.get("cookie_count"),
+ )
+ if not (isinstance(profile_id, str) and isinstance(name, str) and isinstance(site, str) and isinstance(count, int)):
+ return None
+ return SignedInProfile(browser_profile_id=profile_id, profile_name=name, site=site, cookie_count=count)
+
+
+def _decode_credential_response(raw: Any) -> tuple[str, str | None, str | None, SignedInProfile | None] | None:
try:
data = json.loads(raw)
except (TypeError, ValueError):
return None
- if not isinstance(data, dict) or data.get("action") not in ("connected", "skip"):
+ if not isinstance(data, dict) or data.get("action") not in ("connected", "skip", "signed_in"):
return None
credential_id = data.get("credential_id")
resume_token = data.get("resume_token")
@@ -346,9 +484,114 @@ def _decode_credential_response(raw: Any) -> tuple[str, str | None, str | None]
data["action"],
credential_id if isinstance(credential_id, str) else None,
resume_token if isinstance(resume_token, str) else None,
+ _decode_signed_in(data.get("signed_in")),
)
+def sign_in_site(login_urls: list[str]) -> str:
+ return next((host for url in login_urls if (host := (urlparse(url).hostname or "").lower())), "")
+
+
+def manual_sign_in_profile_name(site: str, workflow_title: str | None) -> str:
+ title = defang_card_text(workflow_title or "")
+ return f"Sign-in for {site} ({title})" if title else f"Sign-in for {site}"
+
+
+async def start_manual_sign_in(
+ cache: BaseCache,
+ *,
+ organization_id: str,
+ workflow_copilot_chat_id: str,
+ turn_id: str,
+ resume_token: str,
+) -> datetime:
+ """Restart the pause countdown, once, for a user signing in themselves; returns the new deadline."""
+ active_key = credential_pause_active_key(organization_id, workflow_copilot_chat_id, turn_id)
+ async with cache.get_lock(_credential_pause_lock_key(organization_id, workflow_copilot_chat_id, turn_id)):
+ record = _validate_pending_pause(_decode_active_pause(await cache.get(active_key)), resume_token)
+ sign_in = record.manual_sign_in
+ if sign_in is None:
+ raise CredentialPauseRejection(
+ status_code=HTTPStatus.CONFLICT,
+ detail="This credential card does not offer signing in yourself",
+ )
+ if sign_in.started:
+ return record.expires_at
+ expires_at = max(
+ record.expires_at,
+ datetime.now(timezone.utc) + timedelta(seconds=settings.WORKFLOW_COPILOT_MANUAL_SIGN_IN_TIMEOUT_SECONDS),
+ )
+ # The recovered card must carry the record's deadline, or pending_credential_requests drops it.
+ card = record.card.model_copy(update={"expires_at": expires_at, "signing_in": True}) if record.card else None
+ record = replace(record, expires_at=expires_at, card=card, manual_sign_in=replace(sign_in, started=True))
+ await cache.set(active_key, _encode_record(record), ex=_longest_credential_pause_record_ttl())
+ return expires_at
+
+
+@dataclass(frozen=True)
+class ManualSignInClaim:
+ claim_id: str
+ resume_token: str
+ sign_in: ManualSignIn
+
+
+async def claim_manual_sign_in(
+ cache: BaseCache,
+ *,
+ organization_id: str,
+ workflow_copilot_chat_id: str,
+ turn_id: str,
+ resume_token: str,
+) -> ManualSignInClaim:
+ """Reserve a pending sign-in card for one Done while its profile is saved outside the pause lock."""
+ active_key = credential_pause_active_key(organization_id, workflow_copilot_chat_id, turn_id)
+ async with cache.get_lock(_credential_pause_lock_key(organization_id, workflow_copilot_chat_id, turn_id)):
+ record = _validate_pending_pause(_decode_active_pause(await cache.get(active_key)), resume_token)
+ if record.manual_sign_in is None:
+ raise CredentialPauseRejection(
+ status_code=HTTPStatus.CONFLICT,
+ detail="This credential card does not offer signing in yourself",
+ )
+ claim_id = secrets.token_hex(16)
+ claimed = replace(
+ record,
+ status="resolving",
+ claim_id=claim_id,
+ claim_deadline=datetime.now(timezone.utc) + timedelta(seconds=MANUAL_SIGN_IN_CLAIM_SECONDS),
+ )
+ await cache.set(active_key, _encode_record(claimed), ex=_longest_credential_pause_record_ttl())
+ return ManualSignInClaim(claim_id=claim_id, resume_token=record.resume_token, sign_in=record.manual_sign_in)
+
+
+async def finish_manual_sign_in(
+ cache: BaseCache,
+ *,
+ organization_id: str,
+ workflow_copilot_chat_id: str,
+ turn_id: str,
+ claim: ManualSignInClaim,
+ signed_in: SignedInProfile | None,
+) -> bool:
+ """Settle a Done claim; False means the claim was lost and the caller must discard the profile."""
+ active_key = credential_pause_active_key(organization_id, workflow_copilot_chat_id, turn_id)
+ async with cache.get_lock(_credential_pause_lock_key(organization_id, workflow_copilot_chat_id, turn_id)):
+ record = _decode_active_pause(await cache.get(active_key))
+ if record is None or record.status != "resolving" or record.claim_id != claim.claim_id:
+ return False
+ ttl = _longest_credential_pause_record_ttl()
+ if signed_in is None:
+ reopened = replace(record, status="pending", claim_id=None, claim_deadline=None)
+ await cache.set(active_key, _encode_record(reopened), ex=ttl)
+ return True
+ await cache.set(active_key, _encode_active_pause(record.resume_token, record.expires_at, consumed=True), ex=ttl)
+ await cache.set(
+ credential_response_cache_key(organization_id, workflow_copilot_chat_id, turn_id),
+ encode_credential_response("signed_in", None, record.resume_token, signed_in=signed_in),
+ ex=ttl,
+ )
+ return True
+
+
def credential_pause_reason(ctx: Any) -> str | None:
"""Typed-signal-only detector for a mid-build credential ask.
@@ -473,6 +716,32 @@ def _apply_connected_credential_to_policy(ctx: Any, policy: RequestPolicy, crede
policy.credential_draft_deferred_explicitly = False
+def _apply_signed_in_profile_to_policy(ctx: Any, policy: RequestPolicy, signed_in: SignedInProfile) -> None:
+ """Record the user's own sign-in as this turn's answer: its profile may seed this turn's runs, and the
+ credential ask is settled, without any credential entering the authority plane."""
+ policy.credential_pause_signed_in_profile_id = signed_in.browser_profile_id
+ policy.credential_pause_signed_in_site = signed_in.site
+ policy.clarification_reason = "none"
+ policy.requires_user_clarification = False
+ policy.credential_draft_deferred_explicitly = False
+ ctx.test_after_update_done = False
+ policy.allow_run_blocks = True
+ LOG.info(
+ "copilot_credential_pause_signed_in",
+ browser_profile_id=signed_in.browser_profile_id,
+ site=signed_in.site,
+ cookie_count=signed_in.cookie_count,
+ )
+
+
+def signed_in_facts(signed_in: SignedInProfile) -> str:
+ return (
+ f"The user signed in to {signed_in.site} themselves in the live browser via the credential card. "
+ f"Skyvern saved that sign-in as browser profile {defang_card_text(signed_in.profile_name)} "
+ f"({signed_in.browser_profile_id}) with {signed_in.cookie_count} cookies. No credential was provided."
+ )
+
+
def _assemble_resume_messages(ctx: Any, text: str) -> list[dict[str, Any]]:
# Local import avoids a module-load cycle: enforcement.py imports
# maybe_credential_pause at module scope.
@@ -508,12 +777,14 @@ async def _try_resolve_credential_response(
decoded = _decode_credential_response(raw)
if decoded is None:
return "pending"
- action, credential_id, answered_token = decoded
+ action, credential_id, answered_token, signed_in = decoded
# The response key is per turn, so a card only takes an answer carrying its own token.
if answered_token != resume_token:
return "pending"
if action == "skip":
return CredentialPauseResolution(action="skip")
+ if action == "signed_in":
+ return CredentialPauseResolution(action="signed_in", signed_in=signed_in) if signed_in else None
if not credential_id:
return None
existing = await app.DATABASE.credentials.get_credentials_by_ids([credential_id], organization_id=organization_id)
@@ -526,9 +797,9 @@ async def _wait_for_credential_response(
response_key: str,
ctx: CopilotContext,
stream: EventSourceStream,
- timeout_seconds: int,
+ timeout_seconds: float,
resume_token: str,
-) -> CredentialPauseResolution | None:
+) -> CredentialPauseResolution | None | Literal["disconnected"]:
recovery_enabled = _credential_recovery_enabled(ctx)
# Check once before the sleep loop so a card response posted in the brief
# window before the first poll doesn't cost a full extra poll interval.
@@ -537,7 +808,13 @@ async def _wait_for_credential_response(
return first
deadline = time.monotonic() + timeout_seconds
- while time.monotonic() < deadline:
+ while True:
+ if time.monotonic() >= deadline:
+ # A sign-in the user started, or a Done being saved, moves the record's deadline past ours.
+ remaining = await _seconds_left_on_pause(ctx, resume_token)
+ if remaining <= 0:
+ return None
+ deadline = time.monotonic() + remaining
await asyncio.sleep(CREDENTIAL_RESPONSE_POLL_SECONDS)
# Resolve before checking disconnect: an already-posted response must win
# over a disconnect that happened after the POST (e.g. connect-then-refresh),
@@ -546,8 +823,33 @@ async def _wait_for_credential_response(
if resolved != "pending":
return resolved
if not recovery_enabled and await stream.is_disconnected():
- return None
- return None
+ return "disconnected"
+
+
+async def _seconds_left_on_pause(ctx: CopilotContext, resume_token: str) -> float:
+ key = credential_pause_active_key(ctx.organization_id, ctx.workflow_copilot_chat_id or "", ctx.turn_id or "")
+ record = _decode_active_pause(await app.CACHE.get(key))
+ live_until = record.live_until() if record is not None and record.resume_token == resume_token else None
+ return (live_until - datetime.now(timezone.utc)).total_seconds() if live_until is not None else 0.0
+
+
+def _manual_sign_in_offer(ctx: CopilotContext, login_page_urls: list[str]) -> ManualSignIn | None:
+ """A pick card offers signing in yourself in the editor's live browser when there is one to sign in to."""
+ policy = ctx.request_policy
+ site = sign_in_site(login_page_urls)
+ if (
+ not ctx.browser_session_id
+ or not site
+ or ctx.credential_origin_recovery is not None
+ or (isinstance(policy, RequestPolicy) and policy.raw_secret_detected)
+ ):
+ return None
+ title = ctx.last_workflow.title if ctx.last_workflow is not None else ctx.opening_workflow_title
+ return ManualSignIn(
+ browser_session_id=ctx.browser_session_id,
+ login_urls=list(login_page_urls),
+ profile_name=manual_sign_in_profile_name(site, title),
+ )
async def _run_credential_pause(
@@ -613,6 +915,11 @@ async def _run_credential_pause(
turn_id = ctx.turn_id or ""
resume_token = _new_resume_token()
expires_at = now + timedelta(seconds=timeout_seconds)
+ manual_sign_in = None if update_ask else _manual_sign_in_offer(ctx, login_page_urls)
+ if manual_sign_in is not None:
+ # Signing in takes minutes in the same tab, so the card must survive a reload.
+ ctx.credential_recovery_armed = True
+ recovery_enabled = _credential_recovery_enabled(ctx)
# Establish the active-pause record before the frame carries the token: the
# response endpoint refuses to resolve a turn that has no pending record.
# expires_at is the same deadline the frame tells the client -- the record's
@@ -629,6 +936,7 @@ async def _run_credential_pause(
timeout_seconds=timeout_seconds,
expires_at=expires_at,
anchor_tool_call_id=anchor_tool_call_id,
+ sign_in_browser_session_id=manual_sign_in.browser_session_id if manual_sign_in else None,
timestamp=now,
)
await cache.set(
@@ -638,12 +946,15 @@ async def _run_credential_pause(
expires_at,
card=card if recovery_enabled else None,
recovery_token_digest=ctx.credential_recovery_token_digest if recovery_enabled else None,
+ manual_sign_in=manual_sign_in,
),
- ex=_credential_pause_record_ttl(timeout_seconds),
+ ex=_longest_credential_pause_record_ttl() if manual_sign_in else _credential_pause_record_ttl(timeout_seconds),
)
await stream.send(card)
- async def _invalidate_active_pause_record() -> CredentialPauseResolution | None:
+ async def _invalidate_active_pause_record(
+ *, keep_live: bool = False
+ ) -> CredentialPauseResolution | None | Literal["live"]:
# The waiter can exit (disconnect, genuine timeout, cancellation, or an
# unexpected error) well before expires_at -- invalidate the record so a
# late POST (e.g. the tab reconnects) gets a clear 409 instead of silently
@@ -657,16 +968,27 @@ async def _run_credential_pause(
raced_in = await _try_resolve_credential_response(response_key, organization_id, resume_token)
if isinstance(raced_in, CredentialPauseResolution):
return raced_in
+ active_key = credential_pause_active_key(organization_id, chat_id, turn_id)
+ record = _decode_active_pause(await cache.get(active_key))
+ live_until = record.live_until() if record is not None and record.resume_token == resume_token else None
+ if keep_live and live_until is not None and datetime.now(timezone.utc) < live_until:
+ return "live"
await cache.set(
- credential_pause_active_key(organization_id, chat_id, turn_id),
+ active_key,
_encode_active_pause(resume_token, expires_at, consumed=True),
- ex=_credential_pause_record_ttl(timeout_seconds),
+ ex=_longest_credential_pause_record_ttl()
+ if manual_sign_in
+ else _credential_pause_record_ttl(timeout_seconds),
)
return None
response_key = credential_response_cache_key(organization_id, chat_id, turn_id)
- async def answered(outcome: CredentialPauseResolvedOutcome, credential: Credential | None = None) -> None:
+ async def answered(
+ outcome: CredentialPauseResolvedOutcome,
+ credential: Credential | None = None,
+ signed_in: SignedInProfile | None = None,
+ ) -> None:
# Reaches only the tab holding this turn's stream; a reloaded tab reads the turn-end credentialPause stamp.
await stream.send(
WorkflowCopilotCredentialPauseResolvedUpdate(
@@ -675,11 +997,14 @@ async def _run_credential_pause(
resume_token=resume_token,
outcome=outcome,
credential_id=credential.credential_id if credential else None,
- name=credential.name if credential else None,
+ name=credential.name if credential else signed_in.profile_name if signed_in else None,
+ browser_profile_id=signed_in.browser_profile_id if signed_in else None,
timestamp=datetime.now(timezone.utc),
)
)
+ invalidated = False
+ resolution: CredentialPauseResolution | None = None
if not recovery_enabled and await stream.is_disconnected():
# Legacy clients cannot restore a dropped frame, so preserve their
# immediate decline when disconnect races the send.
@@ -689,9 +1014,22 @@ async def _run_credential_pause(
try:
with pause_human_input(ctx, "credential"):
- resolution = await _wait_for_credential_response(
- response_key, ctx, stream, timeout_seconds, resume_token=resume_token
- )
+ wait_seconds: float = timeout_seconds
+ while True:
+ waited = await _wait_for_credential_response(
+ response_key, ctx, stream, wait_seconds, resume_token=resume_token
+ )
+ resolution = None if isinstance(waited, str) else waited
+ if waited is not None:
+ break
+ # The waiter's last look can race a sign-in start or a Done claim; settle that under the lock.
+ settled = await _invalidate_active_pause_record(keep_live=True)
+ if isinstance(settled, str):
+ wait_seconds = await _seconds_left_on_pause(ctx, resume_token)
+ continue
+ resolution = settled
+ invalidated = True
+ break
except BaseException:
# Covers CancelledError (a direct BaseException subclass, not Exception)
# alongside any unexpected failure in the wait loop itself -- the frame's
@@ -709,11 +1047,12 @@ async def _run_credential_pause(
except Exception:
LOG.warning("Could not record the credential pause resume on the turn marker", exc_info=True)
+ if resolution is None and not invalidated:
+ invalidated_resolution = await _invalidate_active_pause_record()
+ resolution = invalidated_resolution if isinstance(invalidated_resolution, CredentialPauseResolution) else None
if resolution is None:
- resolution = await _invalidate_active_pause_record()
- if resolution is None:
- settle("timeout")
- return None
+ settle("timeout")
+ return None
if resolution.action == "skip":
settle("skipped")
if not update_ask:
@@ -724,6 +1063,16 @@ async def _run_credential_pause(
await answered("skipped")
return resolution
+ if resolution.action == "signed_in":
+ if resolution.signed_in is None or update_ask:
+ settle("timeout")
+ return None
+ if isinstance(policy, RequestPolicy):
+ _apply_signed_in_profile_to_policy(ctx, policy, resolution.signed_in)
+ ctx.credential_pause_outcome = "signed_in"
+ await answered("signed_in", signed_in=resolution.signed_in)
+ return resolution
+
credential = resolution.credential
if credential is None:
settle("timeout")
@@ -798,7 +1147,7 @@ async def request_credential_pause(
anchor_tool_call_id=anchor_tool_call_id,
)
if not update_ask:
- ctx.credential_pause_reaskable_by_run = resolution is None or resolution.action != "connected"
+ ctx.credential_pause_reaskable_by_run = resolution is None or resolution.action == "skip"
return resolution
finally:
ctx.credential_ask_in_flight = False
@@ -815,8 +1164,9 @@ async def await_pending_credential_pause(ctx: Any) -> None:
# A call the SDK rejects on its arguments arms the gate without ever reaching the handler that
# releases it, and the stream cannot exit to run the enforcement backstop while this wait is
# parked inside it. Bound the wait so that strands one tool call rather than the whole turn.
+ bound = longest_credential_pause_seconds() + 30
try:
- await asyncio.wait_for(settled.wait(), settings.WORKFLOW_COPILOT_CREDENTIAL_PAUSE_TIMEOUT_SECONDS + 30)
+ await asyncio.wait_for(settled.wait(), bound)
except asyncio.TimeoutError:
LOG.warning("copilot_credential_gate_wait_timed_out")
settled.set()
@@ -863,6 +1213,8 @@ async def maybe_credential_pause(
return None
if resolution.action == "skip":
return _assemble_resume_messages(ctx, _SKIP_RESUME_TEXT)
+ if resolution.signed_in is not None:
+ return _assemble_resume_messages(ctx, signed_in_facts(resolution.signed_in))
credential = resolution.credential
if credential is None:
return None
diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.py
index 21aa234a3..791de7637 100644
--- a/skyvern/forge/sdk/copilot/request_policy.py
+++ b/skyvern/forge/sdk/copilot/request_policy.py
@@ -970,6 +970,10 @@ class RequestPolicy:
# canvas, which carries a copilot proposal the user has not accepted, so it cannot grant a run.
persisted_workflow_credential_ids: list[str] = field(default_factory=list)
persisted_workflow_browser_profile_id: str | None = None
+ # The profile saved from the user's own sign-in on this turn's credential card, and its site. It may
+ # seed this turn's test runs before Accept saves it as the workflow's pick.
+ credential_pause_signed_in_profile_id: str | None = None
+ credential_pause_signed_in_site: str | None = None
# Active Google OAuth connections admitted only for workflow execution. These never enter
# resolved_credentials, which remains the password-fill authority plane from ADR 0002.
run_approved_google_connection_ids: list[str] = field(default_factory=list)
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index f785d62a0..aa7f434ed 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -995,10 +995,12 @@ async def request_credential_tool(
credential_id: str | None = None,
rejected_by_site: bool = False,
) -> str:
- """Ask the user, in chat, to add or pick a saved credential for a sign-in page.
+ """Ask the user, in chat, how to sign in to a sign-in page: add or pick a saved credential, or
+ sign in themselves in the live browser and save that sign-in as a browser profile.
Use this instead of a prose question when a login still needs selection or setup, including
- a sign-in page discovered while navigating. Reuse the user's existing choice, the saved
+ a sign-in page discovered while navigating, or a saved browser profile whose sign-in no longer
+ reaches past the sign-in page. Reuse the user's existing choice, the saved
workflow's binding, or an unambiguous website match without asking again when it can fill.
`login_page_url` is the absolute HTTP(S) sign-in URL shown on the card; selecting a credential
authorizes it for that site. `reason` is one sentence explaining why the login is needed.
@@ -1010,7 +1012,9 @@ async def request_credential_tool(
comes back `updated` once they save; re-run the sign-in then.
The call waits for the user's answer and comes back `connected` with the credential
to bind, `skipped`, `unanswered`, or `unavailable` — follow the `next` or `fallback` it
- carries. Each turn allows one ask to pick a login and one ask to update a chosen credential.
+ carries. It comes back `signed_in` when the user signed in themselves in the live browser:
+ no credential was provided, and the result names the browser profile that saved the sign-in.
+ Each turn allows one ask to pick a login and one ask to update a chosen credential.
"""
copilot_ctx = ctx.context
arguments = {
@@ -1175,7 +1179,8 @@ async def run_blocks_tool(
Block labels must match labels in the saved workflow.
A run that starts at the first block opens a fresh browser loaded with the saved browser
profile, if any, that a normal run of the saved workflow would load. A profile that is only
- staged in a proposal is not loaded until the workflow is saved with it.
+ staged in a proposal is not loaded until the workflow is saved with it, except the profile the
+ user saved by signing in from the credential card this turn: a draft that selects it loads it now.
If an existing saved block can establish the state you need, run that
block unchanged before scouting the resulting page. In particular, a saved
diff --git a/skyvern/forge/sdk/copilot/tools/credential_fill.py b/skyvern/forge/sdk/copilot/tools/credential_fill.py
index a2fdb72c4..5f0f1b571 100644
--- a/skyvern/forge/sdk/copilot/tools/credential_fill.py
+++ b/skyvern/forge/sdk/copilot/tools/credential_fill.py
@@ -736,6 +736,16 @@ async def _request_credential(
"parameter placeholder in the draft and do not ask again this turn."
),
}
+ if resolution.signed_in is not None:
+ return {
+ "ok": True,
+ "status": "signed_in",
+ "site": resolution.signed_in.site,
+ "browser_profile_id": resolution.signed_in.browser_profile_id,
+ "browser_profile_name": defang_card_text(resolution.signed_in.profile_name),
+ "cookie_count": resolution.signed_in.cookie_count,
+ "credential_provided": False,
+ }
if resolution.action == "connected" and credential is None:
return {
"ok": True,
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 6f1eeebb5..80d8209ac 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -3997,9 +3997,15 @@ async def _run_blocks_and_collect_debug(
if seed_approval_error is not None:
return {"ok": False, "error": seed_approval_error}
if preview is not None and preview[1] == BrowserSeedSource.picked:
- # A draft can name any profile in the org; only the saved workflow's pick at turn start is settled.
- saved_pick = ctx.request_policy.persisted_workflow_browser_profile_id if ctx.request_policy else None
- if preview[0] != saved_pick:
+ # A draft can name any profile in the org; only the saved workflow's pick at turn start, or the
+ # profile the user's own sign-in saved on this turn's card, is settled.
+ policy = ctx.request_policy
+ settled_picks = (
+ {policy.persisted_workflow_browser_profile_id, policy.credential_pause_signed_in_profile_id} - {None}
+ if policy
+ else set()
+ )
+ if preview[0] not in settled_picks:
return {"ok": False, "error": _UNSAVED_BROWSER_PROFILE_PICK_ERROR}
if preview is not None:
seed_profile_id, browser_seed_source = preview
diff --git a/skyvern/forge/sdk/routes/browser_profiles.py b/skyvern/forge/sdk/routes/browser_profiles.py
index 4b9641877..01e6c3059 100644
--- a/skyvern/forge/sdk/routes/browser_profiles.py
+++ b/skyvern/forge/sdk/routes/browser_profiles.py
@@ -1,5 +1,7 @@
import asyncio
+import secrets
import shutil
+from datetime import UTC, datetime
from pathlib import Path as FilePath
from typing import Any, NoReturn
@@ -16,6 +18,7 @@ from skyvern.exceptions import (
)
from skyvern.forge import app
from skyvern.forge.sdk.api.files import discard_temp_working_dir, make_temp_directory
+from skyvern.forge.sdk.credential_site_policy import same_release_scope
from skyvern.forge.sdk.routes.code_samples import (
CREATE_BROWSER_PROFILE_CODE_SAMPLE_PYTHON,
CREATE_BROWSER_PROFILE_CODE_SAMPLE_TS,
@@ -43,6 +46,7 @@ from skyvern.schemas.proxy_pinning import apply_proxy_pin_update as _apply_proxy
from skyvern.schemas.proxy_pinning import should_generate_proxy_session_id
from skyvern.schemas.runs import ProxyLocation, ProxyLocationInput
from skyvern.webeye.browser_profile_utils import FRESH_PROFILE_COPY_IGNORE, valid_operator_profile_generation
+from skyvern.webeye.profile_cookie_merge import cookies_for_login_urls, sanitize_cookies, write_signin_cookies
LOG = structlog.get_logger()
@@ -653,10 +657,13 @@ async def _create_empty_profile(
description: str | None,
proxy_location: ProxyLocationInput = None,
proxy_session_id: str | None = None,
+ seed_cookies: list[dict] | None = None,
) -> BrowserProfile:
# Seed before inserting so local setup failures never reserve a profile name.
profile_dir = _create_empty_browser_profile_directory()
try:
+ if seed_cookies:
+ write_signin_cookies(profile_dir, seed_cookies)
try:
profile = await app.DATABASE.browser_sessions.create_browser_profile(
organization_id=organization_id,
@@ -674,7 +681,8 @@ async def _create_empty_profile(
profile_id=profile.browser_profile_id,
directory=profile_dir,
)
- except Exception:
+ # BaseException: a caller's timeout cancels mid-store, and the row must not outlive its files.
+ except BaseException:
rolled_back = await _hard_delete_created_profile_after_store_failure(
organization_id=organization_id,
browser_profile_id=profile.browser_profile_id,
@@ -698,6 +706,70 @@ async def _create_empty_profile(
return profile
+async def create_profile_from_running_session(
+ *,
+ organization_id: str,
+ browser_session_id: str,
+ login_urls: list[str],
+ name: str,
+ description: str | None,
+) -> tuple[BrowserProfile | None, int]:
+ """Save a live session's cookies for the sign-in hosts as a new profile; ``(None, 0)`` means none matched.
+
+ Raises when the live browser cannot be read, so callers can tell a failed read from an empty one.
+ """
+ browser_session = await app.DATABASE.browser_sessions.get_persistent_browser_session(
+ browser_session_id, organization_id
+ )
+ if browser_session is None:
+ raise BrowserSessionNotFound(browser_session_id)
+ browser_state = await app.PERSISTENT_SESSIONS_MANAGER.get_observer_browser_state(
+ browser_session_id, organization_id
+ )
+ if browser_state is None or browser_state.browser_context is None:
+ raise RuntimeError(f"The live browser for {browser_session_id} is not reachable")
+ try:
+ page = await browser_state.get_working_page(prune_excess_pages=False)
+ candidates = [*login_urls, page.url] if page is not None else list(login_urls)
+ # Only the site the card names: an identity provider's or another tab's cookies never ride along.
+ hosts = [url for url in candidates if login_urls and same_release_scope(url, login_urls[0])]
+ cookies = sanitize_cookies(cookies_for_login_urls(await browser_state.browser_context.cookies(), hosts))
+ finally:
+ await app.PERSISTENT_SESSIONS_MANAGER.release_observer_browser_state(browser_session_id, browser_state)
+ if not cookies:
+ return None, 0
+
+ proxy_location, proxy_session_id = _normalize_proxy_pin_fields(
+ proxy_location=browser_session.proxy_location,
+ proxy_session_id=browser_session.proxy_session_id,
+ )
+ # Each renewed sign-in adds a profile under the same name, so a taken name goes straight to a dated one.
+ stamp = f"{datetime.now(UTC):%Y-%m-%d %H:%M:%S}"
+ candidates = [name, f"{name} ({stamp})", f"{name} ({stamp} {secrets.token_hex(2)})"]
+ for candidate in candidates:
+ try:
+ profile = await _create_empty_profile(
+ organization_id=organization_id,
+ name=candidate,
+ description=description,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ seed_cookies=cookies,
+ )
+ break
+ except HTTPException as exc:
+ if exc.status_code != status.HTTP_409_CONFLICT or candidate == candidates[-1]:
+ raise
+ LOG.info(
+ "Created browser profile from running session",
+ organization_id=organization_id,
+ browser_profile_id=profile.browser_profile_id,
+ browser_session_id=browser_session_id,
+ cookie_count=len(cookies),
+ )
+ return profile, len(cookies)
+
+
async def _create_profile_from_session(
*,
organization_id: str,
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.py
index ae262352c..f9faa3dd2 100644
--- a/skyvern/forge/sdk/routes/workflow_copilot.py
+++ b/skyvern/forge/sdk/routes/workflow_copilot.py
@@ -31,6 +31,7 @@ from skyvern.forge.sdk.api.llm.api_handler import LLMAPIHandler
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderError
from skyvern.forge.sdk.artifact.models import ArtifactType, LogEntityType
from skyvern.forge.sdk.browser_action_policy import canonicalize_origin
+from skyvern.forge.sdk.cache.base import BaseCache
from skyvern.forge.sdk.copilot.agent import run_copilot_agent
from skyvern.forge.sdk.copilot.ask_user import QuestionInteraction, QuestionResponse, question_wait_is_live
from skyvern.forge.sdk.copilot.browser_ablation import CopilotEvalMode
@@ -47,11 +48,17 @@ from skyvern.forge.sdk.copilot.context import (
merge_approved_credentials_into_global_llm_context,
)
from skyvern.forge.sdk.copilot.credential_pause import (
+ MANUAL_SIGN_IN_SAVE_TIMEOUT_SECONDS,
CredentialPauseRejection,
+ SignedInProfile,
check_credential_pause_resumable,
+ claim_manual_sign_in,
credential_pause_is_active,
+ finish_manual_sign_in,
pending_credential_requests,
resolve_credential_pause,
+ sign_in_site,
+ start_manual_sign_in,
)
from skyvern.forge.sdk.copilot.credential_resolution import safe_admitted_url
from skyvern.forge.sdk.copilot.enforcement import TOTAL_TIMEOUT_SECONDS
@@ -108,6 +115,10 @@ from skyvern.forge.sdk.db.exceptions import (
NotFoundError,
)
from skyvern.forge.sdk.forge_log import _generated_log_value
+from skyvern.forge.sdk.routes.browser_profiles import (
+ _hard_delete_created_profile_after_store_failure,
+ create_profile_from_running_session,
+)
from skyvern.forge.sdk.routes.routers import base_router
from skyvern.forge.sdk.schemas.copilot_turn_outcome import PersistedCopilotComposerMode, ResponseKind, TurnOutcome
from skyvern.forge.sdk.schemas.organizations import Organization
@@ -135,6 +146,7 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatSummary,
WorkflowCopilotClearProposedWorkflowRequest,
WorkflowCopilotCredentialResponseRequest,
+ WorkflowCopilotCredentialResponseResult,
WorkflowCopilotDisableAutoAcceptRequest,
WorkflowCopilotGoalSuggestionRequest,
WorkflowCopilotGoalSuggestionResponse,
@@ -4104,13 +4116,69 @@ async def workflow_copilot_cancel(
)
+async def _resolve_manual_sign_in(
+ cache: BaseCache, organization_id: str, response_request: WorkflowCopilotCredentialResponseRequest
+) -> WorkflowCopilotCredentialResponseResult:
+ pause_ids = {
+ "organization_id": organization_id,
+ "workflow_copilot_chat_id": response_request.workflow_copilot_chat_id,
+ "turn_id": response_request.turn_id,
+ }
+ claim = await claim_manual_sign_in(cache, resume_token=response_request.resume_token, **pause_ids)
+ site = sign_in_site(claim.sign_in.login_urls)
+ signed_in: SignedInProfile | None = None
+ save_failed = False
+ try:
+ profile, cookie_count = await asyncio.wait_for(
+ create_profile_from_running_session(
+ organization_id=organization_id,
+ browser_session_id=claim.sign_in.browser_session_id,
+ login_urls=claim.sign_in.login_urls,
+ name=claim.sign_in.profile_name,
+ description="Saved when you signed in yourself from the Copilot credential card.",
+ ),
+ MANUAL_SIGN_IN_SAVE_TIMEOUT_SECONDS,
+ )
+ if profile is not None:
+ signed_in = SignedInProfile(
+ browser_profile_id=profile.browser_profile_id,
+ profile_name=profile.name,
+ site=site,
+ cookie_count=cookie_count,
+ )
+ except Exception:
+ save_failed = True
+ LOG.warning("copilot_credential_pause_sign_in_save_failed", exc_info=True)
+ if not await finish_manual_sign_in(cache, claim=claim, signed_in=signed_in, **pause_ids):
+ if signed_in is not None:
+ await _hard_delete_created_profile_after_store_failure(
+ organization_id=organization_id, browser_profile_id=signed_in.browser_profile_id
+ )
+ try:
+ await app.STORAGE.delete_browser_profile(
+ organization_id=organization_id, profile_id=signed_in.browser_profile_id, hard_delete=True
+ )
+ except Exception:
+ LOG.warning("Failed to delete an unclaimed sign-in profile's stored cookies", exc_info=True)
+ raise CredentialPauseRejection(status_code=status.HTTP_409_CONFLICT, detail="Credential pause already resolved")
+ if signed_in is None:
+ return WorkflowCopilotCredentialResponseResult(
+ result="save_failed" if save_failed else "no_sign_in_found", host=site
+ )
+ return WorkflowCopilotCredentialResponseResult(
+ result="signed_in", host=site, browser_profile_id=signed_in.browser_profile_id
+ )
+
+
@base_router.post(
- "/workflow/copilot/credential-response", include_in_schema=False, status_code=status.HTTP_204_NO_CONTENT
+ "/workflow/copilot/credential-response",
+ include_in_schema=False,
+ response_model=WorkflowCopilotCredentialResponseResult,
)
async def workflow_copilot_credential_response(
response_request: WorkflowCopilotCredentialResponseRequest,
organization: Organization = Depends(org_auth_service.get_current_org),
-) -> None:
+) -> WorkflowCopilotCredentialResponseResult:
"""Resume a turn paused on ``credential_required`` with the user's card response.
The resume path is not authorized by org auth + ``turn_id`` alone: the caller
@@ -4120,6 +4188,8 @@ async def workflow_copilot_credential_response(
503 when ``app.CACHE`` is absent, 422 when ``action="connected"`` omits a
``credential_id``, 404 when that ID doesn't resolve in this organization or no
active pause matches, 403 on a bad token, and 409 once the pause is consumed.
+ ``signing_in`` restarts the countdown once; ``signed_in`` saves the live browser's sign-in as a
+ profile and answers ``no_sign_in_found`` (no cookies for the site) or ``save_failed`` without resuming.
"""
cache = getattr(app, "CACHE", None)
if cache is None:
@@ -4143,6 +4213,21 @@ async def workflow_copilot_credential_response(
except CredentialPauseRejection as rejection:
raise HTTPException(status_code=rejection.status_code, detail=rejection.detail)
+ try:
+ if response_request.action == "signing_in":
+ expires_at = await start_manual_sign_in(
+ cache,
+ organization_id=organization.organization_id,
+ workflow_copilot_chat_id=response_request.workflow_copilot_chat_id,
+ turn_id=response_request.turn_id,
+ resume_token=response_request.resume_token,
+ )
+ return WorkflowCopilotCredentialResponseResult(result="accepted", expires_at=expires_at)
+ if response_request.action == "signed_in":
+ return await _resolve_manual_sign_in(cache, organization.organization_id, response_request)
+ except CredentialPauseRejection as rejection:
+ raise HTTPException(status_code=rejection.status_code, detail=rejection.detail)
+
credential_id = response_request.credential_id
if response_request.action == "connected":
if not credential_id:
@@ -4168,6 +4253,7 @@ async def workflow_copilot_credential_response(
)
except CredentialPauseRejection as rejection:
raise HTTPException(status_code=rejection.status_code, detail=rejection.detail)
+ return WorkflowCopilotCredentialResponseResult(result="accepted")
@base_router.post(
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index 62c7dbb69..4e1dbc1a6 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -532,10 +532,23 @@ class WorkflowCopilotCredentialResponseRequest(BaseModel):
turn_id: str = Field(..., description="turn_id from the matching credential_required frame")
workflow_copilot_chat_id: str = Field(..., description="chat ID from the matching credential_required frame")
resume_token: str = Field(..., description="One-time resume token from the matching credential_required frame")
- action: Literal["connected", "skip"] = Field(..., description="The user's response to the credential card")
+ action: Literal["connected", "skip", "signing_in", "signed_in"] = Field(
+ ...,
+ description=(
+ "The user's response to the credential card: 'signing_in' when they start signing in themselves in "
+ "the live browser, 'signed_in' when they finish"
+ ),
+ )
credential_id: str | None = Field(None, description="Saved credential ID; required when action is 'connected'")
+class WorkflowCopilotCredentialResponseResult(BaseModel):
+ result: Literal["accepted", "signed_in", "no_sign_in_found", "save_failed"]
+ expires_at: datetime | None = Field(None, description="The pause's new deadline after 'signing_in'")
+ host: str | None = Field(None, description="The sign-in site the browser cookies were read for")
+ browser_profile_id: str | None = Field(None, description="The profile saved from the user's sign-in")
+
+
class WorkflowCopilotClearProposedWorkflowRequest(BaseModel):
workflow_copilot_chat_id: str = Field(..., description="The chat ID to update")
auto_accept: bool = Field(..., description="Whether to auto-accept future workflow updates")
@@ -971,10 +984,14 @@ class WorkflowCopilotCredentialRequiredUpdate(BaseModel):
anchor_tool_call_id: str | None = Field(
None, description="Tool call whose activity row was newest when the pause was raised"
)
+ sign_in_browser_session_id: str | None = Field(
+ None, description="The live browser the user may sign in to themselves; absent when the card does not offer it"
+ )
+ signing_in: bool = Field(False, description="The user has started signing in themselves")
timestamp: datetime = Field(..., description="Server timestamp")
-CredentialPauseResolvedOutcome = Literal["connected", "skipped", "not_admitted"]
+CredentialPauseResolvedOutcome = Literal["connected", "skipped", "not_admitted", "signed_in"]
class WorkflowCopilotCredentialPauseResolvedUpdate(BaseModel):
@@ -988,7 +1005,10 @@ class WorkflowCopilotCredentialPauseResolvedUpdate(BaseModel):
..., description="The waiter's final verdict, after admission; never the raw POSTed action"
)
credential_id: str | None = Field(None, description="The connected credential; set only when connected")
- name: str | None = Field(None, description="Display name of the connected credential; set only when connected")
+ name: str | None = Field(
+ None, description="Display name of the connected credential, or of the profile saved from a sign-in"
+ )
+ browser_profile_id: str | None = Field(None, description="The profile saved from the user's own sign-in")
timestamp: datetime = Field(..., description="Server timestamp")
diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.py
index 4631001f6..dc69d1e3d 100644
--- a/skyvern/webeye/browser_factory.py
+++ b/skyvern/webeye/browser_factory.py
@@ -91,7 +91,11 @@ from skyvern.webeye.display_recorder import (
release_started_display_recording,
)
from skyvern.webeye.playwright_input import register_playwright_input_context
-from skyvern.webeye.session_cookies import restore_banked_cookies, restore_session_cookies
+from skyvern.webeye.session_cookies import (
+ restore_banked_cookies,
+ restore_session_cookies,
+ restore_signin_cookies,
+)
LOG = structlog.get_logger()
@@ -820,6 +824,7 @@ class BrowserContextFactory:
organization_id=kwargs.get("organization_id"),
)
await restore_session_cookies(browser_context, browser_artifacts.browser_session_dir)
+ await restore_signin_cookies(browser_context, browser_artifacts.browser_session_dir)
# After session cookies so a verified-login heal (banked by the credential living-profile
# engine) wins over the profile's own older session cookies on a key clash. Gated on the
# engine kill-switch so a rollback also stops applying previously banked login state.
diff --git a/skyvern/webeye/browser_profile_utils.py b/skyvern/webeye/browser_profile_utils.py
index f33546197..4ac616054 100644
--- a/skyvern/webeye/browser_profile_utils.py
+++ b/skyvern/webeye/browser_profile_utils.py
@@ -3,7 +3,7 @@ import os
import stat
import tempfile
-from skyvern.webeye.profile_cookie_merge import BANKED_COOKIES_FILENAME
+from skyvern.webeye.profile_cookie_merge import BANKED_COOKIES_FILENAME, SIGNIN_COOKIES_FILENAME
from skyvern.webeye.session_cookies import SESSION_COOKIES_FILENAME
DEFAULT_PROFILE_COPY_IGNORE = {
@@ -30,7 +30,11 @@ DEFAULT_PROFILE_COPY_IGNORE = {
# must never carry Skyvern's login-cookie sidecars — a contaminated template would restore another run's
# (cross-org) session cookies into a "fresh" browser, or bake them permanently into a stored profile.
# Reuse paths that return a profile dir directly never go through a copy, so they keep their cookies.
-FRESH_PROFILE_COPY_IGNORE = DEFAULT_PROFILE_COPY_IGNORE | {SESSION_COOKIES_FILENAME, BANKED_COOKIES_FILENAME}
+FRESH_PROFILE_COPY_IGNORE = DEFAULT_PROFILE_COPY_IGNORE | {
+ SESSION_COOKIES_FILENAME,
+ BANKED_COOKIES_FILENAME,
+ SIGNIN_COOKIES_FILENAME,
+}
def operator_profile_generation(path: str) -> str | None:
diff --git a/skyvern/webeye/profile_cookie_merge.py b/skyvern/webeye/profile_cookie_merge.py
index 5c377bee4..a1955a67f 100644
--- a/skyvern/webeye/profile_cookie_merge.py
+++ b/skyvern/webeye/profile_cookie_merge.py
@@ -9,12 +9,15 @@ which sidesteps Chromium ``Cookies`` SQLite surgery (no encryption/schema/patchr
import contextlib
import json
import os
+from urllib.parse import urlparse
import structlog
LOG = structlog.get_logger()
BANKED_COOKIES_FILENAME = ".skyvern_banked_cookies.json"
+# A one-shot seed written by an explicit profile create; boot restores it regardless of the memory engine.
+SIGNIN_COOKIES_FILENAME = ".skyvern_signin_cookies.json"
# Keys accepted by Playwright's add_cookies; drop anything else (e.g. partitionKey) so one
# unexpected field can't reject the whole batch. Single source — session_cookies imports this.
@@ -92,6 +95,11 @@ def union_cookies_into_profile_dir(
os.remove(path)
return 0
+ _write_cookie_file(path, cookies)
+ return len(cookies)
+
+
+def _write_cookie_file(path: str, cookies: list[dict]) -> None:
# 0o600: the sidecar holds auth cookies. Write to a temp file and atomically replace so a
# failed write can't leave a partial file or destroy the previous good sidecar.
tmp = f"{path}.tmp"
@@ -103,7 +111,38 @@ def union_cookies_into_profile_dir(
finally:
with contextlib.suppress(FileNotFoundError):
os.remove(tmp)
- return len(cookies)
+
+
+def sanitize_cookies(cookies: list[dict]) -> list[dict]:
+ return [c for c in (_sanitize(cookie) for cookie in cookies) if c is not None]
+
+
+def write_signin_cookies(profile_dir: str, cookies: list[dict]) -> int:
+ """Write ``cookies`` as the profile's sign-in seed sidecar and return the count written."""
+ sanitized = sanitize_cookies(cookies)
+ if not sanitized:
+ return 0
+ _write_cookie_file(os.path.join(profile_dir, SIGNIN_COOKIES_FILENAME), sanitized)
+ return len(sanitized)
+
+
+def cookie_applies_to_host(cookie_domain: str | None, host: str) -> bool:
+ d = (cookie_domain or "").lstrip(".").lower()
+ return bool(d) and (host == d or host.endswith("." + d))
+
+
+def cookies_for_login_urls(cookies: list[dict], login_urls: list[str]) -> list[dict]:
+ """Keep only cookies that apply to a login URL's host or its parent domains.
+
+ Fails CLOSED: with no usable login host nothing is kept, rather than every origin's cookies.
+ """
+ # Sibling-subdomain and cross-domain-SSO cookies fall out in v1 (those logins re-auth).
+ hosts = {host for url in login_urls if (host := (urlparse(url).hostname or "").lower())}
+ return [c for c in cookies if any(cookie_applies_to_host(c.get("domain"), host) for host in hosts)]
+
+
+def cookies_for_login_host(cookies: list[dict], login_url: str | None) -> list[dict]:
+ return cookies_for_login_urls(cookies, [login_url] if login_url else [])
def cookie_delta(end_state_cookies: list[dict], seed_cookies: list[dict]) -> list[dict]:
diff --git a/skyvern/webeye/session_cookies.py b/skyvern/webeye/session_cookies.py
index 979dca5e1..e1cd2dd3c 100644
--- a/skyvern/webeye/session_cookies.py
+++ b/skyvern/webeye/session_cookies.py
@@ -10,6 +10,7 @@ from playwright.async_api import BrowserContext
from skyvern.webeye.profile_cookie_merge import (
_ALLOWED_COOKIE_KEYS,
BANKED_COOKIES_FILENAME,
+ SIGNIN_COOKIES_FILENAME,
clear_banked_cookies,
union_cookies_into_profile_dir,
)
@@ -73,11 +74,13 @@ def read_persisted_session_cookies(user_data_dir: str | None) -> list[dict]:
return [{k: v for k, v in c.items() if k in _ALLOWED_COOKIE_KEYS} for c in cookies if isinstance(c, dict)]
-async def _add_cookies_with_fallback(browser_context: BrowserContext, cookies: list[dict], kind: str) -> None:
- """add_cookies as one batch, falling back to per-cookie so a single bad cookie can't drop the rest."""
+async def _add_cookies_with_fallback(browser_context: BrowserContext, cookies: list[dict], kind: str) -> int:
+ """add_cookies as one batch, falling back to per-cookie so a single bad cookie can't drop the rest.
+ Returns how many cookies were restored."""
try:
await browser_context.add_cookies(cookies)
LOG.info("Restored cookies into browser profile", kind=kind, cookie_count=len(cookies), sampling=True)
+ return len(cookies)
except Exception:
restored = 0
for cookie in cookies:
@@ -94,6 +97,7 @@ async def _add_cookies_with_fallback(browser_context: BrowserContext, cookies: l
failed=len(cookies) - restored,
total=len(cookies),
)
+ return restored
async def restore_session_cookies(browser_context: BrowserContext | None, user_data_dir: str | None) -> None:
@@ -120,19 +124,15 @@ async def restore_session_cookies(browser_context: BrowserContext | None, user_d
LOG.warning("Failed to restore session cookies", exc_info=True)
-async def restore_banked_cookies(browser_context: BrowserContext | None, user_data_dir: str | None) -> None:
- """Re-inject cookies unioned by ``profile_cookie_merge.union_cookies_into_profile_dir``.
-
- Called AFTER ``restore_session_cookies`` so a verified-login heal wins over the profile's own
- older session sidecar on a (domain, name, path) clash. Persistent expiries are preserved;
- session expiries (-1/0) are pinned to -1 for the same patchright reason as restore_session_cookies.
- """
+async def _restore_cookie_sidecar(
+ browser_context: BrowserContext | None, user_data_dir: str | None, filename: str, kind: str
+) -> int:
try:
if browser_context is None or not user_data_dir or not os.path.isdir(user_data_dir):
- return
- path = os.path.join(user_data_dir, BANKED_COOKIES_FILENAME)
+ return 0
+ path = os.path.join(user_data_dir, filename)
if not os.path.exists(path):
- return
+ return 0
with open(path) as f:
cookies = json.load(f)
sanitized = [
@@ -144,10 +144,29 @@ async def restore_banked_cookies(browser_context: BrowserContext | None, user_da
if cookie.get("name") and cookie.get("domain")
]
if not sanitized:
- return
- await _add_cookies_with_fallback(browser_context, sanitized, "banked")
+ return 0
+ return await _add_cookies_with_fallback(browser_context, sanitized, kind)
except Exception:
- LOG.warning("Failed to restore banked cookies", exc_info=True)
+ LOG.warning("Failed to restore cookies", kind=kind, exc_info=True)
+ return 0
+
+
+async def restore_banked_cookies(browser_context: BrowserContext | None, user_data_dir: str | None) -> None:
+ """Re-inject cookies unioned by ``profile_cookie_merge.union_cookies_into_profile_dir``.
+
+ Called AFTER ``restore_session_cookies`` so a verified-login heal wins over the profile's own
+ older session sidecar on a (domain, name, path) clash. Persistent expiries are preserved;
+ session expiries (-1/0) are pinned to -1 for the same patchright reason as restore_session_cookies.
+ """
+ await _restore_cookie_sidecar(browser_context, user_data_dir, BANKED_COOKIES_FILENAME, "banked")
+
+
+async def restore_signin_cookies(browser_context: BrowserContext | None, user_data_dir: str | None) -> None:
+ """Re-inject a profile's sign-in seed, then delete it so a later write-back archives the live jar
+ instead of carrying the seed forward to replay over fresher cookies."""
+ if await _restore_cookie_sidecar(browser_context, user_data_dir, SIGNIN_COOKIES_FILENAME, "signin"):
+ with contextlib.suppress(OSError):
+ os.remove(os.path.join(user_data_dir or "", SIGNIN_COOKIES_FILENAME))
async def refresh_banked_cookies(browser_context: BrowserContext | None, user_data_dir: str | None) -> None:
diff --git a/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py b/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
index fa0f8bcfa..77598a443 100644
--- a/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
+++ b/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
@@ -2,6 +2,9 @@
from __future__ import annotations
+import asyncio
+import json
+import re
from collections.abc import Iterator
from datetime import datetime
from pathlib import Path
@@ -23,6 +26,7 @@ from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrow
from skyvern.forge.sdk.services import org_auth_service
from skyvern.schemas.runs import ProxyLocation
from skyvern.webeye.browser_profile_utils import operator_profile_generation, write_operator_profile_marker
+from skyvern.webeye.profile_cookie_merge import SIGNIN_COOKIES_FILENAME
_default_profile_template_candidates = browser_profiles_route._default_browser_profile_template_candidates
@@ -83,12 +87,18 @@ def _build_client(
rate_limit_submit_run=AsyncMock(),
get_workflow_browser_session_storage_key=AsyncMock(return_value="wp_1"),
engine_enabled=AsyncMock(return_value=True),
+ observe_session=AsyncMock(),
+ release_observed_session=AsyncMock(),
)
forge_app.set_app(
SimpleNamespace(
AGENT_FUNCTION=SimpleNamespace(is_browser_memory_engine_enabled_for_org=mocks.engine_enabled),
RATE_LIMITER=SimpleNamespace(rate_limit_submit_run=mocks.rate_limit_submit_run),
+ PERSISTENT_SESSIONS_MANAGER=SimpleNamespace(
+ get_observer_browser_state=mocks.observe_session,
+ release_observer_browser_state=mocks.release_observed_session,
+ ),
WORKFLOW_SERVICE=SimpleNamespace(
get_workflow_browser_session_storage_key=mocks.get_workflow_browser_session_storage_key,
),
@@ -422,6 +432,49 @@ def test_create_empty_profile_rolls_back_when_archive_store_fails(monkeypatch: p
mocks.delete_db_profile.assert_not_awaited()
+async def test_running_session_profile_dates_a_taken_name_instead_of_overwriting(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _client, mocks = _build_client(monkeypatch)
+ mocks.get_session.return_value = _session()
+ mocks.observe_session.return_value = _running_browser(
+ [{"name": "sid", "value": "1", "domain": "portal.example.com", "path": "/"}],
+ page_url="https://portal.example.com/members",
+ )
+ duplicate = IntegrityError("insert", {}, Exception("duplicate"))
+ mocks.create_profile.side_effect = [duplicate, duplicate, _profile()]
+
+ profile, _count = await browser_profiles_route.create_profile_from_running_session(
+ organization_id="org_oss",
+ browser_session_id="pbs_1",
+ login_urls=["https://portal.example.com/login"],
+ name="Sign-in for portal.example.com",
+ description=None,
+ )
+
+ assert profile == _profile()
+ names = [call.kwargs["name"] for call in mocks.create_profile.await_args_list]
+ stamp = r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"
+ assert names[0] == "Sign-in for portal.example.com"
+ assert re.fullmatch(rf"Sign-in for portal\.example\.com \({stamp}\)", names[1])
+ assert re.fullmatch(rf"Sign-in for portal\.example\.com \({stamp} [0-9a-f]{{4}}\)", names[2])
+ mocks.store_profile.assert_awaited_once()
+
+
+async def test_create_empty_profile_rolls_back_when_a_timeout_cancels_the_store(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _, mocks = _build_client(monkeypatch)
+ mocks.store_profile.side_effect = asyncio.CancelledError()
+
+ with pytest.raises(asyncio.CancelledError):
+ await browser_profiles_route._create_empty_profile(organization_id="org_oss", name="n", description=None)
+
+ mocks.hard_delete_db_profile.assert_awaited_once_with("bp_new", organization_id="org_oss")
+
+
def test_create_empty_profile_preserves_store_error_when_rollback_fails(monkeypatch: pytest.MonkeyPatch) -> None:
client, mocks = _build_client(monkeypatch, raise_server_exceptions=True)
mocks.store_profile.side_effect = RuntimeError("s3 upload failed")
@@ -883,3 +936,135 @@ async def test_persisted_state_dir_exports_engine_sink_for_picked_plain(monkeypa
await retrieve_persisted_workflow_browser_state_dir(organization_id="o", workflow=workflow, workflow_run=run)
is None
)
+
+
+def _running_browser(cookies: list[dict], page_url: str) -> SimpleNamespace:
+ context = SimpleNamespace(cookies=AsyncMock(return_value=cookies), close=AsyncMock())
+ page = SimpleNamespace(url=page_url)
+ return SimpleNamespace(browser_context=context, get_working_page=AsyncMock(return_value=page), close=AsyncMock())
+
+
+def _capture_signin_seed(mocks: SimpleNamespace) -> list[list[dict]]:
+ seeds: list[list[dict]] = []
+
+ async def _store(*, organization_id: str, profile_id: str, directory: str) -> None:
+ seeds.append(json.loads((Path(directory) / SIGNIN_COOKIES_FILENAME).read_text()))
+
+ mocks.store_profile.side_effect = _store
+ return seeds
+
+
+async def test_running_session_profile_saves_sign_in_cookies_and_leaves_session_open(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _client, mocks = _build_client(monkeypatch)
+ mocks.get_session.return_value = _session(proxy_location=ProxyLocation.RESIDENTIAL_ISP, proxy_session_id="ps_1")
+ browser = _running_browser(
+ [
+ {"name": "sid", "value": "1", "domain": "portal.example.com", "path": "/"},
+ {"name": "member", "value": "2", "domain": "members.example.com", "path": "/"},
+ {"name": "ad", "value": "3", "domain": "tracker.example.org", "path": "/"},
+ ],
+ page_url="https://members.example.com/home",
+ )
+ mocks.observe_session.return_value = browser
+ seeds = _capture_signin_seed(mocks)
+
+ profile, count = await browser_profiles_route.create_profile_from_running_session(
+ organization_id="org_oss",
+ browser_session_id="pbs_1",
+ login_urls=["https://portal.example.com/login"],
+ name="Sign-in for portal.example.com",
+ description=None,
+ )
+
+ assert (profile, count) == (_profile(), 2)
+ assert [c["name"] for c in seeds[0]] == ["sid", "member"]
+ assert mocks.create_profile.await_args.kwargs["proxy_session_id"] == "ps_1"
+ mocks.release_observed_session.assert_awaited_once_with("pbs_1", browser)
+ browser.get_working_page.assert_awaited_once_with(prune_excess_pages=False)
+ browser.close.assert_not_awaited()
+ browser.browser_context.close.assert_not_awaited()
+ mocks.retrieve_profile.assert_not_awaited()
+ mocks.delete_profile_blob.assert_not_awaited()
+
+
+ ("login_urls", "page_url"),
+ [
+ (["https://app.example.com/login"], "https://accounts.example.net/signin/consent"),
+ (["https://app.example.com/login", "https://accounts.example.net/o/oauth2"], "https://app.example.com/home"),
+ ],
+)
+async def test_running_session_profile_keeps_only_the_named_sites_cookies(
+ monkeypatch: pytest.MonkeyPatch, login_urls: list[str], page_url: str
+) -> None:
+ _client, mocks = _build_client(monkeypatch)
+ mocks.get_session.return_value = _session()
+ mocks.observe_session.return_value = _running_browser(
+ [
+ {"name": "app_sid", "value": "1", "domain": "app.example.com", "path": "/"},
+ {"name": "SID", "value": "2", "domain": ".example.net", "path": "/"},
+ ],
+ page_url=page_url,
+ )
+ seeds = _capture_signin_seed(mocks)
+
+ await browser_profiles_route.create_profile_from_running_session(
+ organization_id="org_oss",
+ browser_session_id="pbs_1",
+ login_urls=login_urls,
+ name="Sign-in for app.example.com",
+ description=None,
+ )
+
+ assert [c["name"] for c in seeds[0]] == ["app_sid"]
+
+
+async def test_running_session_profile_raises_when_the_live_browser_is_unreachable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _client, mocks = _build_client(monkeypatch)
+ mocks.get_session.return_value = _session()
+ mocks.observe_session.return_value = None
+
+ with pytest.raises(RuntimeError, match="not reachable"):
+ await browser_profiles_route.create_profile_from_running_session(
+ organization_id="org_oss",
+ browser_session_id="pbs_1",
+ login_urls=["https://portal.example.com/login"],
+ name="Sign-in for portal.example.com",
+ description=None,
+ )
+
+ mocks.create_profile.assert_not_awaited()
+
+
+async def test_running_session_profile_without_matching_cookie_writes_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _client, mocks = _build_client(monkeypatch)
+ mocks.get_session.return_value = _session()
+ browser = _running_browser(
+ [{"name": "ad", "value": "3", "domain": "tracker.example.org", "path": "/"}],
+ page_url="https://portal.example.com/login",
+ )
+ mocks.observe_session.return_value = browser
+
+ result = await browser_profiles_route.create_profile_from_running_session(
+ organization_id="org_oss",
+ browser_session_id="pbs_1",
+ login_urls=["https://portal.example.com/login"],
+ name="Sign-in for portal.example.com",
+ description=None,
+ )
+
+ assert result == (None, 0)
+ mocks.create_profile.assert_not_awaited()
+ mocks.store_profile.assert_not_awaited()
+ mocks.release_observed_session.assert_awaited_once_with("pbs_1", browser)
+ browser.browser_context.close.assert_not_awaited()
diff --git a/tests/unit/test_browser_context_factory_marker.py b/tests/unit/test_browser_context_factory_marker.py
index 34324f28e..e7b557230 100644
--- a/tests/unit/test_browser_context_factory_marker.py
+++ b/tests/unit/test_browser_context_factory_marker.py
@@ -26,6 +26,7 @@ from skyvern.webeye import display_recorder as dr
from skyvern.webeye.browser_artifacts import BrowserArtifacts, VideoArtifact
from skyvern.webeye.browser_factory import BrowserContextFactory
from skyvern.webeye.playwright_input import playwright_input_defaults_for_page
+from skyvern.webeye.profile_cookie_merge import write_signin_cookies
@pytest.mark.asyncio
@@ -169,6 +170,27 @@ async def test_create_browser_context_gates_playwright_video_on_acquired_recorde
assert listener.called is expect_listener
+async def test_factory_restores_sign_in_seed_with_banked_cookies_off(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ write_signin_cookies(str(tmp_path), [{"name": "sid", "value": "1", "domain": "portal.example.com", "path": "/"}])
+ context = MagicMock()
+ context.add_cookies = AsyncMock()
+
+ async def _creator(playwright: Any, **kwargs: Any) -> tuple[Any, BrowserArtifacts, None]:
+ return context, BrowserArtifacts(browser_session_dir=str(tmp_path)), None
+
+ _factory_harness(monkeypatch)
+ BrowserContextFactory.register_type("test-signin-seed", _creator)
+ monkeypatch.setattr(factory_module.settings, "BROWSER_TYPE", "test-signin-seed")
+
+ await BrowserContextFactory.create_browser_context(playwright=object())
+
+ assert [c["name"] for c in context.add_cookies.await_args.args[0]] == ["sid"]
+ factory_module.restore_banked_cookies.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_factory_registers_authoritative_playwright_input_defaults(monkeypatch: pytest.MonkeyPatch) -> None:
context = MagicMock()
diff --git a/tests/unit/test_copilot_credential_pause.py b/tests/unit/test_copilot_credential_pause.py
index 2511621e7..4056f00c9 100644
--- a/tests/unit/test_copilot_credential_pause.py
+++ b/tests/unit/test_copilot_credential_pause.py
@@ -1158,7 +1158,7 @@ async def test_route_503_when_cache_missing(monkeypatch: pytest.MonkeyPatch) ->
@pytest.mark.asyncio
-async def test_route_204_writes_flag_for_skip_without_credential_id(monkeypatch: pytest.MonkeyPatch) -> None:
+async def test_route_writes_flag_for_skip_without_credential_id(monkeypatch: pytest.MonkeyPatch) -> None:
cache = _FakeCache()
_seed_active_pause(cache, "org-1", "chat-1", "turn-1", "tok-1")
monkeypatch.setattr(app._inst, "CACHE", cache, raising=False)
@@ -1166,7 +1166,7 @@ async def test_route_204_writes_flag_for_skip_without_credential_id(monkeypatch:
result = await workflow_copilot_credential_response(_response_request(action="skip"), organization=organization)
- assert result is None
+ assert result.result == "accepted"
expected_key = credential_response_cache_key("org-1", "chat-1", "turn-1")
assert cache.store[expected_key] == encode_credential_response("skip", None, "tok-1")
response_set = next(call for call in cache.set_calls if call[0] == expected_key)
@@ -1209,7 +1209,7 @@ async def test_route_404_when_credential_unknown_or_foreign_org(monkeypatch: pyt
@pytest.mark.asyncio
-async def test_route_204_writes_flag_for_connected_with_valid_credential(monkeypatch: pytest.MonkeyPatch) -> None:
+async def test_route_writes_flag_for_connected_with_valid_credential(monkeypatch: pytest.MonkeyPatch) -> None:
cache = _FakeCache()
_seed_active_pause(cache, "org-1", "chat-1", "turn-1", "tok-1")
monkeypatch.setattr(app._inst, "CACHE", cache, raising=False)
@@ -1227,7 +1227,7 @@ async def test_route_204_writes_flag_for_connected_with_valid_credential(monkeyp
organization=organization,
)
- assert result is None
+ assert result.result == "accepted"
expected_key = credential_response_cache_key("org-1", "chat-1", "turn-1")
assert cache.store[expected_key] == encode_credential_response("connected", "cred_1", "tok-1")
@@ -1308,7 +1308,7 @@ async def test_route_409_on_replay_after_first_accepted_response(monkeypatch: py
organization = SimpleNamespace(organization_id="org-1")
first = await workflow_copilot_credential_response(_response_request(action="skip"), organization=organization)
- assert first is None
+ assert first.result == "accepted"
with pytest.raises(HTTPException) as excinfo:
await workflow_copilot_credential_response(_response_request(action="skip"), organization=organization)
@@ -2858,3 +2858,39 @@ async def test_the_finalize_seam_opens_no_card_on_a_redacted_secret_draft(monkey
)
def test_the_raw_secret_card_sees_only_the_origin(user_url: str, origin: str) -> None:
assert credential_pause_module.raw_secret_card_origin(user_url) == origin
+
+
+async def test_a_run_derived_card_answered_by_signing_in_resumes_with_facts_and_does_not_fire_again(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = make_copilot_context()
+ ctx.organization_id = "org-1"
+ ctx.turn_id = "turn-1"
+ ctx.workflow_copilot_chat_id = "chat-1"
+ ctx.client_supports_credential_pause = True
+ ctx.last_run_skipped_unbound_credentials = True
+ ctx.request_policy = RequestPolicy(
+ login_page_urls=["https://portal.example.com/login"], credential_draft_deferred_explicitly=True
+ )
+ signed_in = credential_pause_module.SignedInProfile(
+ browser_profile_id="bp_signed_in",
+ profile_name="Sign-in for portal.example.com",
+ site="portal.example.com",
+ cookie_count=2,
+ )
+ cache = _FakeCache()
+ cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response(
+ "signed_in", None, "tok-1", signed_in=signed_in
+ )
+ monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
+ monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
+ config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)
+
+ resume_msgs = await maybe_credential_pause(ctx, _fake_result(), _make_stream(), config)
+
+ assert resume_msgs is not None
+ assert credential_pause_module.signed_in_facts(signed_in) in json.dumps(resume_msgs)
+ assert ctx.credential_pause_outcome == "signed_in"
+ assert credential_prompt_reason(ctx.request_policy, None) is None
+ assert await maybe_credential_pause(ctx, _fake_result(), _make_stream(), config) is None
diff --git a/tests/unit/test_copilot_credential_pause_reload.py b/tests/unit/test_copilot_credential_pause_reload.py
index 37a1e568a..ac616f3b0 100644
--- a/tests/unit/test_copilot_credential_pause_reload.py
+++ b/tests/unit/test_copilot_credential_pause_reload.py
@@ -1,16 +1,19 @@
import asyncio
-from datetime import UTC
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
+from structlog.testing import capture_logs
+from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.sdk.copilot import credential_pause as pauses
from skyvern.forge.sdk.copilot.config import CopilotConfig
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy, _ground_user_provided_sites
from skyvern.forge.sdk.copilot.tools.credential_fill import _request_credential
from skyvern.forge.sdk.routes import workflow_copilot as routes
+from skyvern.forge.sdk.schemas.browser_profiles import BrowserProfile
from tests.unit.test_copilot_ask_user import setup_question_chat
from tests.unit.test_copilot_credential_pause import _FakeCache, _make_credential, _make_stream
@@ -133,8 +136,6 @@ async def test_disconnected_card_recovers_through_authenticated_history_and_resu
@pytest.mark.asyncio
@pytest.mark.parametrize("ending", ["expired", "cancelled"])
async def test_history_hides_expired_or_cancelled_recoverable_card(sqlite_engine, monkeypatch, ending):
- from datetime import datetime, timedelta
-
_, client, ctx, _ = await setup_question_chat(sqlite_engine, monkeypatch)
cache = _FakeCache()
monkeypatch.setattr(app, "CACHE", cache)
@@ -201,3 +202,207 @@ async def test_pending_credential_requests_propagates_redis_failure(monkeypatch)
with pytest.raises(RuntimeError, match="redis unavailable"):
await pauses.pending_credential_requests("org", "chat", ["turn"], "a" * 64)
+
+
+def _signed_in_profile() -> BrowserProfile:
+ now = datetime.now(UTC)
+ return BrowserProfile(
+ browser_profile_id="bp_signed_in",
+ organization_id="org",
+ name="Sign-in for portal.example.com",
+ created_at=now,
+ modified_at=now,
+ )
+
+
+def _sign_in_card_context(ctx, *, recovery: bool):
+ ctx.browser_session_id = "pbs_debug"
+ ctx.client_supports_credential_pause = True
+ ctx.client_supports_credential_pause_recovery = recovery
+ ctx.credential_recovery_armed = False
+ ctx.credential_recovery_token_digest = pauses.credential_recovery_token_digest("a" * 64) if recovery else None
+ ctx.copilot_config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)
+ ctx.request_policy = RequestPolicy(credential_draft_deferred_explicitly=True)
+ _ground_user_provided_sites(ctx.request_policy, "https://portal.example.com/login", [])
+ ctx.stream = _make_stream()
+ emitted = asyncio.Event()
+ ctx.stream.send.side_effect = lambda _: emitted.set()
+ ctx.stream.is_disconnected.side_effect = lambda: recovery and emitted.is_set()
+ return emitted
+
+
+async def test_signing_in_survives_a_reload_and_done_resumes_the_same_call_with_the_saved_profile(
+ sqlite_engine, monkeypatch
+):
+ _, client, ctx, _ = await setup_question_chat(sqlite_engine, monkeypatch)
+ monkeypatch.setattr(app, "CACHE", _FakeCache())
+ monkeypatch.setattr(pauses, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
+ monkeypatch.setattr(routes, "RECONCILE_ABANDON_AFTER_SECONDS", -1)
+ release_first_save = asyncio.Event()
+ save_calls: list[dict] = []
+
+ async def save(**kwargs):
+ save_calls.append(kwargs)
+ if len(save_calls) == 1:
+ await release_first_save.wait()
+ return None, 0
+ if len(save_calls) == 2:
+ raise RuntimeError("The live browser is not reachable")
+ return _signed_in_profile(), 2
+
+ monkeypatch.setattr(routes, "create_profile_from_running_session", save)
+ emitted = _sign_in_card_context(ctx, recovery=True)
+ client._transport.app.add_api_route(
+ "/credential-response", routes.workflow_copilot_credential_response, methods=["POST"]
+ )
+ headers = {"X-Copilot-Credential-Recovery-Token": "a" * 64}
+ params = {"workflow_copilot_chat_id": ctx.workflow_copilot_chat_id}
+ async with client:
+ invocation = asyncio.create_task(_request_credential("https://portal.example.com/login", "Login", ctx))
+ try:
+ await asyncio.wait_for(emitted.wait(), 1)
+ card = ctx.stream.send.await_args.args[0]
+ assert card.sign_in_browser_session_id == "pbs_debug"
+ body = {
+ "workflow_copilot_chat_id": card.workflow_copilot_chat_id,
+ "turn_id": card.turn_id,
+ "resume_token": card.resume_token,
+ }
+
+ started = await client.post("/credential-response", json={**body, "action": "signing_in"})
+ assert started.status_code == 200
+ extended = datetime.fromisoformat(started.json()["expires_at"])
+ manual_window = timedelta(seconds=settings.WORKFLOW_COPILOT_MANUAL_SIGN_IN_TIMEOUT_SECONDS)
+ assert extended - card.expires_at > manual_window - timedelta(seconds=30)
+ again = await client.post("/credential-response", json={**body, "action": "signing_in"})
+ assert datetime.fromisoformat(again.json()["expires_at"]) == extended
+
+ reloaded = (await client.get("/history", params=params, headers=headers)).json()
+ restored = reloaded["pending_credential_requests"][0]
+ assert restored["signing_in"] is True
+ assert datetime.fromisoformat(restored["expires_at"]) == extended
+
+ saving = asyncio.create_task(client.post("/credential-response", json={**body, "action": "signed_in"}))
+ while not save_calls:
+ await asyncio.sleep(0.01)
+ during_save = (await client.get("/history", params=params, headers=headers)).json()
+ assert during_save["pending_credential_requests"][0]["resume_token"] == card.resume_token
+ release_first_save.set()
+ nothing = await saving
+ assert nothing.json() == {
+ "result": "no_sign_in_found",
+ "expires_at": None,
+ "host": "portal.example.com",
+ "browser_profile_id": None,
+ }
+ failed = await client.post("/credential-response", json={**body, "action": "signed_in"})
+ assert failed.json()["result"] == "save_failed"
+ await asyncio.sleep(0.05)
+ assert not invocation.done()
+
+ with capture_logs() as logs:
+ done = await client.post("/credential-response", json={**body, "action": "signed_in"})
+ result = await asyncio.wait_for(invocation, 1)
+ assert done.json()["result"] == "signed_in"
+ assert done.json()["browser_profile_id"] == "bp_signed_in"
+ finally:
+ if not invocation.done():
+ invocation.cancel()
+ await asyncio.gather(invocation, return_exceptions=True)
+
+ assert save_calls[-1]["browser_session_id"] == "pbs_debug"
+ assert save_calls[-1]["login_urls"] == ["https://portal.example.com/login"]
+ assert result["status"] == "signed_in"
+ assert result["browser_profile_id"] == "bp_signed_in"
+ assert result["credential_provided"] is False
+ assert "next" not in result
+ assert ctx.credential_pause_outcome == "signed_in"
+ assert ctx.credential_pause_reaskable_by_run is False
+ assert ctx.request_policy.credential_pause_signed_in_profile_id == "bp_signed_in"
+ assert ctx.request_policy.credential_pause_signed_in_site == "portal.example.com"
+ assert ctx.request_policy.credential_draft_deferred_explicitly is False
+ assert ctx.request_policy.resolved_credentials == []
+ assert any(entry["event"] == "copilot_credential_pause_signed_in" for entry in logs)
+
+
+async def test_done_without_card_recovery_still_resumes_and_a_skip_after_no_sign_in_still_works(
+ sqlite_engine, monkeypatch
+):
+ _, client, ctx, _ = await setup_question_chat(sqlite_engine, monkeypatch)
+ monkeypatch.setattr(app, "CACHE", _FakeCache())
+ monkeypatch.setattr(pauses, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
+ monkeypatch.setattr(routes, "create_profile_from_running_session", AsyncMock(return_value=(None, 0)))
+ emitted = _sign_in_card_context(ctx, recovery=False)
+ client._transport.app.add_api_route(
+ "/credential-response", routes.workflow_copilot_credential_response, methods=["POST"]
+ )
+ async with client:
+ invocation = asyncio.create_task(_request_credential("https://portal.example.com/login", "Login", ctx))
+ try:
+ await asyncio.wait_for(emitted.wait(), 1)
+ card = ctx.stream.send.await_args.args[0]
+ body = {
+ "workflow_copilot_chat_id": card.workflow_copilot_chat_id,
+ "turn_id": card.turn_id,
+ "resume_token": card.resume_token,
+ }
+ nothing = await client.post("/credential-response", json={**body, "action": "signed_in"})
+ assert nothing.json()["result"] == "no_sign_in_found"
+ skipped = await client.post("/credential-response", json={**body, "action": "skip"})
+ assert skipped.status_code == 200
+ result = await asyncio.wait_for(invocation, 1)
+ finally:
+ if not invocation.done():
+ invocation.cancel()
+ await asyncio.gather(invocation, return_exceptions=True)
+
+ assert result["status"] == "skipped"
+ assert ctx.request_policy.credential_pause_signed_in_profile_id is None
+
+
+async def test_a_done_whose_pause_ended_while_saving_discards_the_profile(sqlite_engine, monkeypatch):
+ _, client, ctx, _ = await setup_question_chat(sqlite_engine, monkeypatch)
+ cache = _FakeCache()
+ monkeypatch.setattr(app, "CACHE", cache)
+ monkeypatch.setattr(pauses, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
+ emitted = _sign_in_card_context(ctx, recovery=True)
+ invocation: asyncio.Task | None = None
+
+ async def save_while_the_turn_is_cancelled(**_kwargs):
+ assert invocation is not None
+ invocation.cancel()
+ await asyncio.gather(invocation, return_exceptions=True)
+ return _signed_in_profile(), 2
+
+ monkeypatch.setattr(routes, "create_profile_from_running_session", save_while_the_turn_is_cancelled)
+ hard_delete = AsyncMock(return_value=True)
+ monkeypatch.setattr(routes, "_hard_delete_created_profile_after_store_failure", hard_delete)
+ storage = SimpleNamespace(delete_browser_profile=AsyncMock())
+ monkeypatch.setattr(app, "STORAGE", storage)
+ client._transport.app.add_api_route(
+ "/credential-response", routes.workflow_copilot_credential_response, methods=["POST"]
+ )
+ async with client:
+ invocation = asyncio.create_task(_request_credential("https://portal.example.com/login", "Login", ctx))
+ await asyncio.wait_for(emitted.wait(), 1)
+ card = ctx.stream.send.await_args.args[0]
+ done = await client.post(
+ "/credential-response",
+ json={
+ "workflow_copilot_chat_id": card.workflow_copilot_chat_id,
+ "turn_id": card.turn_id,
+ "resume_token": card.resume_token,
+ "action": "signed_in",
+ },
+ )
+
+ assert done.status_code == 409
+ hard_delete.assert_awaited_once_with(organization_id="org", browser_profile_id="bp_signed_in")
+ storage.delete_browser_profile.assert_awaited_once_with(
+ organization_id="org", profile_id="bp_signed_in", hard_delete=True
+ )
+ response_key = pauses.credential_response_cache_key("org", card.workflow_copilot_chat_id, card.turn_id)
+ assert response_key not in cache.store
diff --git a/tests/unit/test_copy_browser_profile_template.py b/tests/unit/test_copy_browser_profile_template.py
index fa88c7b9a..dce9e1114 100644
--- a/tests/unit/test_copy_browser_profile_template.py
+++ b/tests/unit/test_copy_browser_profile_template.py
@@ -1,7 +1,7 @@
from pathlib import Path
from skyvern.forge.sdk.routes.browser_profiles import _copy_browser_profile_template
-from skyvern.webeye.profile_cookie_merge import BANKED_COOKIES_FILENAME
+from skyvern.webeye.profile_cookie_merge import BANKED_COOKIES_FILENAME, SIGNIN_COOKIES_FILENAME
from skyvern.webeye.session_cookies import SESSION_COOKIES_FILENAME
@@ -14,6 +14,7 @@ def test_copy_browser_profile_template_excludes_cookie_sidecars(tmp_path: Path)
(source / "Local State").write_text("{}")
(source / SESSION_COOKIES_FILENAME).write_text("[]")
(source / BANKED_COOKIES_FILENAME).write_text("[]")
+ (source / SIGNIN_COOKIES_FILENAME).write_text("[]")
dest = tmp_path / "profile"
dest.mkdir()
@@ -22,5 +23,6 @@ def test_copy_browser_profile_template_excludes_cookie_sidecars(tmp_path: Path)
copied = {p.name for p in dest.iterdir()}
assert SESSION_COOKIES_FILENAME not in copied
assert BANKED_COOKIES_FILENAME not in copied
+ assert SIGNIN_COOKIES_FILENAME not in copied
assert "Local State" in copied # a normal file still copies, so the exclusion is targeted
assert (dest / "Default" / "Preferences").exists()
diff --git a/tests/unit/test_profile_cookie_merge.py b/tests/unit/test_profile_cookie_merge.py
index d4d2f343a..d8877f44d 100644
--- a/tests/unit/test_profile_cookie_merge.py
+++ b/tests/unit/test_profile_cookie_merge.py
@@ -10,13 +10,16 @@ from playwright.async_api import BrowserContext
from skyvern.webeye.profile_cookie_merge import (
BANKED_COOKIES_FILENAME,
+ SIGNIN_COOKIES_FILENAME,
_cookie_key,
clear_banked_cookies,
cookie_delta,
+ cookies_for_login_urls,
seed_cookie_values,
union_cookies_into_profile_dir,
+ write_signin_cookies,
)
-from skyvern.webeye.session_cookies import restore_banked_cookies
+from skyvern.webeye.session_cookies import restore_banked_cookies, restore_signin_cookies
_SESSION = {"name": "sess", "value": "a", "domain": "x.com", "path": "/", "expires": -1}
_SESSION_ZERO = {"name": "sess0", "value": "c", "domain": "x.com", "path": "/", "expires": 0}
@@ -213,3 +216,35 @@ def test_three_way_applies_when_current_still_equals_seed(tmp_path: Path) -> Non
ours = [{"name": "sid", "value": "OURS", "domain": "x.com", "path": "/"}]
union_cookies_into_profile_dir(ours, str(tmp_path), base_values=seed_cookie_values(seed))
assert _sidecar_values(tmp_path)[("x.com", "sid", "/")] == "OURS" # base==theirs -> ours applied
+
+
+def test_cookies_for_login_urls_keeps_login_hosts_and_parent_domains() -> None:
+ cookies = [
+ {"name": "a", "domain": ".example.com"},
+ {"name": "b", "domain": "app.example.com"},
+ {"name": "c", "domain": "other.example.org"},
+ {"name": "d", "domain": "sibling.example.com"},
+ ]
+ kept = cookies_for_login_urls(cookies, ["https://app.example.com/login", "not a url"])
+ assert [c["name"] for c in kept] == ["a", "b"]
+ assert cookies_for_login_urls(cookies, []) == []
+
+
+async def test_signin_seed_restores_once_then_is_deleted(tmp_path: Path) -> None:
+ assert write_signin_cookies(str(tmp_path), [_SESSION_ZERO, _PERSISTENT, {"name": "", "domain": "x.com"}]) == 2
+ seed = tmp_path / SIGNIN_COOKIES_FILENAME
+ assert stat.S_IMODE(seed.stat().st_mode) == 0o600
+
+ fake = FakeContext()
+ await restore_signin_cookies(_ctx(fake), str(tmp_path))
+
+ assert {c["name"] for c in fake.added[0]} == {"sess0", "persist"}
+ assert not seed.exists()
+
+
+async def test_signin_seed_is_kept_when_restore_fails(tmp_path: Path) -> None:
+ write_signin_cookies(str(tmp_path), [_PERSISTENT])
+ await restore_signin_cookies(_ctx(RaisingContext()), str(tmp_path))
+ assert (tmp_path / SIGNIN_COOKIES_FILENAME).exists()