Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Show who created each credential and browser session (#8654)
Shuchang Zheng6aac9ff3b494
diff --git a/alembic/versions/2026_09_25_1715-4909d15f6587_add_managed_sms_config_and_phone_fields.py b/alembic/versions/2026_09_25_1715-4909d15f6587_add_managed_sms_config_and_phone_fields.pynew file mode 100644index 000000000..7c6a02e03--- /dev/null+++ b/alembic/versions/2026_09_25_1715-4909d15f6587_add_managed_sms_config_and_phone_fields.py@@ -0,0 +1,93 @@+"""add managed SMS config and phone fields++Revision ID: 4909d15f6587+Revises: 1dc949839af2+Create Date: 2026-09-25T17:15:02.857740+00:00++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "4909d15f6587"+down_revision: Union[str, None] = "1dc949839af2"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None++_LOCK_TIMEOUT = "5s"+++def _replace_phone_number_index() -> None:+ duplicates = (+ op.get_bind()+ .execute(+ sa.text(+ "SELECT phone_number_id FROM ("+ "SELECT phone_number_id, count(*) OVER (PARTITION BY organization_id, phone_number) AS reservation_count "+ "FROM organization_phone_numbers "+ "WHERE status IN ('active', 'provisioning', 'quarantined') AND deleted_at IS NULL "+ ") AS reservations WHERE reservation_count > 1 ORDER BY phone_number_id"+ )+ )+ .scalars()+ .all()+ )+ if duplicates:+ raise RuntimeError(+ f"Duplicate managed phone reservations: {len(duplicates)} rows; phone_number_ids: {duplicates}"+ )+ op.drop_index("uq_org_phone_numbers_org_number", table_name="organization_phone_numbers")+ op.create_index(+ "uq_org_phone_numbers_org_number",+ "organization_phone_numbers",+ ["organization_id", "phone_number"],+ unique=True,+ postgresql_where=sa.text("status IN ('active', 'provisioning', 'quarantined') AND deleted_at IS NULL"),+ sqlite_where=sa.text("status IN ('active', 'provisioning', 'quarantined') AND deleted_at IS NULL"),+ )+++def upgrade() -> None:+ op.get_bind().execute(sa.text(f"SET LOCAL lock_timeout = '{_LOCK_TIMEOUT}'"))+ op.add_column(+ "organization_sms_configs",+ sa.Column("encrypted_signing_token", sa.String(), nullable=True),+ )+ op.add_column(+ "organization_sms_configs",+ sa.Column("signing_token_encrypted_method", sa.String(), nullable=True),+ )+ op.add_column(+ "organization_phone_numbers",+ sa.Column("provisioning_claimed_at", sa.DateTime(), nullable=True),+ )+ op.create_index(+ "uq_org_sms_configs_one_managed",+ "organization_sms_configs",+ ["organization_id"],+ unique=True,+ postgresql_where=sa.text("mode = 'managed' AND deleted_at IS NULL"),+ sqlite_where=sa.text("mode = 'managed' AND deleted_at IS NULL"),+ )+ _replace_phone_number_index()+++def downgrade() -> None:+ op.get_bind().execute(sa.text(f"SET LOCAL lock_timeout = '{_LOCK_TIMEOUT}'"))+ op.drop_index("uq_org_phone_numbers_org_number", table_name="organization_phone_numbers")+ op.create_index(+ "uq_org_phone_numbers_org_number",+ "organization_phone_numbers",+ ["organization_id", "phone_number"],+ unique=True,+ postgresql_where=sa.text("status = 'active' AND deleted_at IS NULL"),+ sqlite_where=sa.text("status = 'active' AND deleted_at IS NULL"),+ )+ op.drop_column("organization_phone_numbers", "provisioning_claimed_at")+ op.drop_index("uq_org_sms_configs_one_managed", table_name="organization_sms_configs")+ op.drop_column("organization_sms_configs", "signing_token_encrypted_method")+ op.drop_column("organization_sms_configs", "encrypted_signing_token")diff --git a/alembic/versions/2026_09_25_1715-dc24a9eab0fb_add_created_by_to_credentials_and_persistent_browser_sessions.py b/alembic/versions/2026_09_25_1715-dc24a9eab0fb_add_created_by_to_credentials_and_persistent_browser_sessions.pynew file mode 100644index 000000000..bcfd6b76d--- /dev/null+++ b/alembic/versions/2026_09_25_1715-dc24a9eab0fb_add_created_by_to_credentials_and_persistent_browser_sessions.py@@ -0,0 +1,31 @@+"""add created_by to credentials and persistent_browser_sessions++Revision ID: dc24a9eab0fb+Revises: 4909d15f6587+Create Date: 2026-09-25T17:15:02.859825+00:00++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "dc24a9eab0fb"+down_revision: Union[str, None] = "4909d15f6587"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.execute("SET LOCAL lock_timeout = '5s'")+ op.add_column("credentials", sa.Column("created_by", sa.String(), nullable=True))+ op.add_column("persistent_browser_sessions", sa.Column("created_by", sa.String(), nullable=True))+++def downgrade() -> None:+ op.execute("SET LOCAL lock_timeout = '5s'")+ op.drop_column("persistent_browser_sessions", "created_by")+ op.drop_column("credentials", "created_by")diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.jsonindex 14455d3e9..393d82ff8 100644--- a/docs/api-reference/openapi.json+++ b/docs/api-reference/openapi.json@@ -11004,6 +11004,18 @@"title": "Completed At","description": "Timestamp when the session was completed"},+ "created_by": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Created By",+ "description": "ID of the user who created the session"+ },"created_at": {"type": "string","format": "date-time",@@ -12731,6 +12743,18 @@],"title": "Proxy Session Id","description": "Opaque Skyvern-managed proxy sticky-session id."+ },+ "created_by": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Created By",+ "description": "ID of the user who created the credential"}},"type": "object",diff --git a/docs/cloud/building-agents/configure-blocks.mdx b/docs/cloud/building-agents/configure-blocks.mdxindex c12acdca1..5ef272a82 100644--- a/docs/cloud/building-agents/configure-blocks.mdx+++ b/docs/cloud/building-agents/configure-blocks.mdx@@ -206,6 +206,8 @@ Additional fields in **Advanced Settings:**Search Google or Exa over an API. Add `site:example.com` to the query to search within a site. This block does not open a browser or read linked pages.+With Google and a single `site:example.com` or `site:example.com/path` filter, the block removes results outside the filter. The block repeats the search up to two times when Google returns only results outside the filter. The block does not remove results when the query has quotation marks, parentheses, `|`, `OR`, or more than one `site:` filter.+| Field | Type | Description || ------------------------- | -------- | ----------------------------------------------------------------------------------------- || **Search Query** | text | Required query. Supports input and output parameter references. |diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.tsindex 7aaf5851a..00d8150e1 100644--- a/skyvern-frontend/src/api/types.ts+++ b/skyvern-frontend/src/api/types.ts@@ -1123,6 +1123,7 @@ export type CredentialApiResponse = {folder_id?: string | null;proxy_location?: ProxyLocation | null;proxy_session_id?: string | null;+ created_by?: string | null;};export function isPasswordCredential(diff --git a/skyvern-frontend/src/components/CreatorDirectoryBoundary.tsx b/skyvern-frontend/src/components/CreatorDirectoryBoundary.tsxnew file mode 100644index 000000000..943e30a70--- /dev/null+++ b/skyvern-frontend/src/components/CreatorDirectoryBoundary.tsx@@ -0,0 +1,18 @@+import type { ReactNode } from "react";++import { usePageSlots } from "@/store/PageSlots";++type Props = {+ children: ReactNode;+};++function CreatorDirectoryBoundary({ children }: Props) {+ const { workflowCreatorDirectory: CreatorDirectory } = usePageSlots();+ return CreatorDirectory ? (+ <CreatorDirectory>{children}</CreatorDirectory>+ ) : (+ <>{children}</>+ );+}++export { CreatorDirectoryBoundary };diff --git a/skyvern-frontend/src/components/FailureCategoryBadge.tsx b/skyvern-frontend/src/components/FailureCategoryBadge.tsxindex c10af3995..38340f17f 100644--- a/skyvern-frontend/src/components/FailureCategoryBadge.tsx+++ b/skyvern-frontend/src/components/FailureCategoryBadge.tsx@@ -1,12 +1,12 @@import type { FailureCategory } from "@/api/types";import { Badge } from "@/components/ui/badge";--function formatCategoryLabel(category: string): string {- return category- .split("_")- .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())- .join(" ");-}+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { getFailureCategoryDisplay } from "@/util/failureCategoryDisplay";type Props = {failureCategory: Array<FailureCategory> | null;@@ -14,13 +14,29 @@ type Props = {function FailureCategoryBadge({ failureCategory }: Props) {const primary = failureCategory?.[0];- if (!primary) {+ // failure_category is untyped JSON on the backend and can carry model output, so guard at runtime.+ if (typeof primary?.category !== "string" || !primary.category.trim()) {return null;}+ const { label, description } = getFailureCategoryDisplay(primary);+ // Self-contained provider so the badge works outside the studio's provider; tabIndex keeps+ // the explanation reachable on keyboard focus, not hover only.return (- <Badge variant="destructive" className="w-fit">- {formatCategoryLabel(primary.category)}- </Badge>+ <TooltipProvider delayDuration={200}>+ <Tooltip>+ <TooltipTrigger asChild>+ <span+ tabIndex={0}+ className="inline-flex w-fit rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"+ >+ <Badge variant="destructive">{label}</Badge>+ </span>+ </TooltipTrigger>+ <TooltipContent side="bottom" className="max-w-xs">+ {description}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>);}diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessions.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessions.tsxindex a56bf1a05..9c7c7904d 100644--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessions.tsx+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessions.tsx@@ -17,6 +17,9 @@ import {DrawerHeader,DrawerTitle,} from "@/components/ui/drawer";+import { CreatorDirectoryBoundary } from "@/components/CreatorDirectoryBoundary";+import { WorkflowCreatorLabel } from "@/routes/workflows/components/WorkflowCreatorLabel";+import { useCreatorColumnEnabled } from "@/store/WorkflowCreatorContext";import { HelpTooltip } from "@/components/HelpTooltip";import { Pill } from "@/components/StatusBadge";import { Input } from "@/components/ui/input";@@ -95,10 +98,12 @@ const EXTENSION_OPTIONS: Array<{},];-function BrowserSessions() {+function BrowserSessionsContent() {const navigate = useNavigate();const [searchParams, setSearchParams] = useSearchParams();const [isDrawerOpen, setIsDrawerOpen] = useState(false);+ const showCreator = useCreatorColumnEnabled();+ const columnCount = showCreator ? 7 : 6;const [sessionOptions, setSessionOptions] = useState<{proxyLocation: ProxyLocation;timeoutMinutes: number | null;@@ -212,9 +217,9 @@ function BrowserSessions() {<Table className="w-full table-fixed"><TableHeader><TableRow>- <TableHead className="w-[22%] truncate">ID</TableHead>- <TableHead className="w-[10%] truncate">Open</TableHead>- <TableHead className="w-[14%]">+ <TableHead className="w-[20%] truncate">ID</TableHead>+ <TableHead className="w-[8%] truncate">Open</TableHead>+ <TableHead className="w-[12%]"><span className="inline-flex items-center gap-1.5">Occupied<HelpTooltip@@ -223,16 +228,28 @@ function BrowserSessions() {/></span></TableHead>- <TableHead className="w-[14%] truncate">Started</TableHead>- <TableHead className="w-[12%] truncate">Timeout</TableHead>- <TableHead className="w-[28%] truncate">CDP Url</TableHead>+ {showCreator && (+ <TableHead className="w-[14%] truncate">Created By</TableHead>+ )}+ <TableHead className="w-[12%] truncate">Started</TableHead>+ <TableHead className="w-[10%] truncate">Timeout</TableHead>+ <TableHead+ className={cn(+ "truncate",+ showCreator ? "w-[24%]" : "w-[38%]",+ )}+ >+ CDP Url+ </TableHead></TableRow></TableHeader><TableBody>{isLoading ? (- <TableMessageRow colSpan={6}>Loading browsers…</TableMessageRow>+ <TableMessageRow colSpan={columnCount}>+ Loading browsers…+ </TableMessageRow>) : browserSessions?.length === 0 ? (- <TableMessageRow colSpan={6}>+ <TableMessageRow colSpan={columnCount}>No browser sessions found</TableMessageRow>) : (@@ -272,6 +289,13 @@ function BrowserSessions() {<TableCell>{browserSession.runnable_id ? <Yes /> : <No />}</TableCell>+ {showCreator && (+ <TableCell>+ <WorkflowCreatorLabel+ createdBy={browserSession.created_by}+ />+ </TableCell>+ )}<TableCellclassName="text-muted-foreground"title={@@ -525,4 +549,12 @@ function BrowserSessions() {);}+function BrowserSessions() {+ return (+ <CreatorDirectoryBoundary>+ <BrowserSessionsContent />+ </CreatorDirectoryBoundary>+ );+}+export { BrowserSessions };diff --git a/skyvern-frontend/src/routes/credentials/CredentialItem.tsx b/skyvern-frontend/src/routes/credentials/CredentialItem.tsxindex 9ef01d83f..4ba62775b 100644--- a/skyvern-frontend/src/routes/credentials/CredentialItem.tsx+++ b/skyvern-frontend/src/routes/credentials/CredentialItem.tsx@@ -6,6 +6,8 @@ import {type CredentialTotpCodeResponse,} from "@/api/types";import { getClient } from "@/api/AxiosClient";+import { WorkflowCreatorLabel } from "@/routes/workflows/components/WorkflowCreatorLabel";+import { useCreatorColumnEnabled } from "@/store/WorkflowCreatorContext";import { SelectionCheckbox } from "@/components/SelectionCheckbox";import { useEffect, useRef, useState } from "react";import { Link } from "react-router-dom";@@ -262,6 +264,7 @@ function CredentialItem({const { additionalTwoFactorMethods = [] } =useCredentialAuthenticatorSupport();const [editModalOpen, setEditModalOpen] = useState(false);+ const showCreator = useCreatorColumnEnabled();const activeTest = useCredentialTestStore((s) =>s.activeTest?.credentialId === credential.credential_id? s.activeTest@@ -477,6 +480,16 @@ function CredentialItem({)}</div>{credentialDetails}+ {showCreator && (+ <div className="w-40 space-y-2 border-l pl-5">+ <p className="text-sm text-neutral-600 dark:text-slate-400">+ Created By+ </p>+ <p className="text-sm">+ <WorkflowCreatorLabel createdBy={credential.created_by} />+ </p>+ </div>+ )}<div className="ml-auto flex gap-1"><TooltipProvider><Tooltip>diff --git a/skyvern-frontend/src/routes/credentials/CredentialsPage.tsx b/skyvern-frontend/src/routes/credentials/CredentialsPage.tsxindex f7309628a..39d32052f 100644--- a/skyvern-frontend/src/routes/credentials/CredentialsPage.tsx+++ b/skyvern-frontend/src/routes/credentials/CredentialsPage.tsx@@ -6,6 +6,7 @@ import {useRef,useState,} from "react";+import { CreatorDirectoryBoundary } from "@/components/CreatorDirectoryBoundary";import { useDebounce } from "use-debounce";import { Button } from "@/components/ui/button";import { TableSearchInput } from "@/components/TableSearchInput";@@ -51,7 +52,7 @@ const TAB_VALUES = [type TabValue = (typeof TAB_VALUES)[number];const DEFAULT_TAB: TabValue = "passwords";-function CredentialsPage() {+function CredentialsPageContent() {const { openModal } = useCredentialModalState();const { startBackgroundTest } = useBackgroundCredentialTest();const [search, setSearch] = useState("");@@ -530,4 +531,12 @@ function CredentialsPage() {);}+function CredentialsPage() {+ return (+ <CreatorDirectoryBoundary>+ <CredentialsPageContent />+ </CreatorDirectoryBoundary>+ );+}+export { CredentialsPage };diff --git a/skyvern-frontend/src/routes/tasks/detail/ScrollableActionList.tsx b/skyvern-frontend/src/routes/tasks/detail/ScrollableActionList.tsxindex 73d401d07..1262a05ba 100644--- a/skyvern-frontend/src/routes/tasks/detail/ScrollableActionList.tsx+++ b/skyvern-frontend/src/routes/tasks/detail/ScrollableActionList.tsx@@ -131,7 +131,7 @@ function ScrollableActionList({)}{action.summary?.outcome && (<div className="break-words text-xs text-slate-400">- <span className="text-slate-500">Outcome: </span>+ <span className="text-slate-500">Result: </span>{action.summary.outcome}</div>)}diff --git a/skyvern-frontend/src/routes/workflows/Workflows.tsx b/skyvern-frontend/src/routes/workflows/Workflows.tsxindex efd62a06b..db6263b5d 100644--- a/skyvern-frontend/src/routes/workflows/Workflows.tsx+++ b/skyvern-frontend/src/routes/workflows/Workflows.tsx@@ -1,14 +1,16 @@+import { CreatorDirectoryBoundary } from "@/components/CreatorDirectoryBoundary";import { useWorkflowsDirectoryTree } from "@/hooks/useWorkflowsDirectoryTree";-import { usePageSlots } from "@/store/PageSlots";import { WorkflowsFlat } from "./WorkflowsFlat";import { WorkflowsTree } from "./WorkflowsTree";function Workflows() {const directoryTreeEnabled = useWorkflowsDirectoryTree();- const { workflowCreatorDirectory: CreatorDirectory } = usePageSlots();- const list = directoryTreeEnabled ? <WorkflowsTree /> : <WorkflowsFlat />;- return CreatorDirectory ? <CreatorDirectory>{list}</CreatorDirectory> : list;+ return (+ <CreatorDirectoryBoundary>+ {directoryTreeEnabled ? <WorkflowsTree /> : <WorkflowsFlat />}+ </CreatorDirectoryBoundary>+ );}export { Workflows };diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsxindex af38ca817..6f69b9462 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx@@ -31,6 +31,7 @@ type HistoryData = {workflow_copilot_chat_id: string | null;chat_history: unknown[];proposed_workflow: Record<string, unknown> | null;+ proposed_workflow_metadata?: Record<string, unknown> | null;auto_accept: boolean;};@@ -869,13 +870,17 @@ describe("WorkflowCopilotChat — recovery poll after a non-terminal stream clos// The server's own clock, deliberately far behind the client's: correlation// must not depend on comparing it to Date.now().- function recoveredHistory(createdAt = "2025-01-01T00:00:00"): HistoryData {+ function recoveredHistory(+ createdAt = "2025-01-01T00:00:00",+ terminalReason?: string,+ ): HistoryData {return historyWithRow({...capturedAiRow,created_at: createdAt,turn_outcome: {...capturedAiRow.turn_outcome,- terminal_reason: "completed",+ terminal_reason:+ terminalReason ?? capturedAiRow.turn_outcome!.terminal_reason,},});}@@ -1713,6 +1718,26 @@ describe("WorkflowCopilotChat — recovery poll after a non-terminal stream clos// A failed transport must check whether the server persisted a new version.expect(workflowGets).toEqual(["/workflows/wpid_1"]);+ await advance(2_000);+ await resolveNextHistory(+ recoveredHistory("2025-01-01T00:00:00", "completed"),+ );+ expect(renderedText()).toContain(capturedAiText);++ await act(async () => {+ await Promise.resolve();+ });+ expect(workflowGets).toEqual(["/workflows/wpid_1", "/workflows/wpid_1"]);+ expect(useWorkflowYamlEditorStore.getState().copilotAcceptance).toBeNull();+ });++ it("confirms uncertain persistence for a normally finished turn, whose terminal_reason is null", async () => {+ hasLocalChanges.current = true;+ await startTurn();+ await closeStreamWithoutTerminal();++ expect(workflowGets).toEqual(["/workflows/wpid_1"]);+await advance(2_000);await resolveNextHistory(recoveredHistory());expect(renderedText()).toContain(capturedAiText);@@ -2312,6 +2337,127 @@ describe("WorkflowCopilotChat — recovery poll after a non-terminal stream closexpect(historyQueue).toHaveLength(0);});+ async function recoverStagedTurn(+ remount: "mid-stream" | "after the drop" | "none",+ options: { terminalReason?: string; errorFrame?: boolean } = {},+ ): Promise<ReturnType<typeof vi.fn>> {+ const snapshot: EditorStateSnapshot = {+ workflowPermanentId: "wpid_1",+ nodes: [],+ edges: [],+ parameters: [],+ title: "Submitted title",+ titleHasBeenGenerated: false,+ description: "",+ hasChanges: false,+ saveGeneration: 0,+ };+ const restore = vi.fn().mockReturnValue("restored");+ const props = {+ captureEditorState: () => snapshot,+ restoreEditorState: restore,+ };+ workflowResponse.current = {+ workflow_id: "wf_1",+ workflow_permanent_id: "wpid_1",+ };+ const staged = {+ workflow_id: "wf_proposed",+ workflow_permanent_id: "wpid_1",+ workflow_definition: { blocks: [], parameters: [] },+ };+ const view = await renderChat(props);+ await flushHistory(historyData());+ await submit("build me a flow");+ await waitFor(() => expect(streamCalls).toHaveLength(1));+ await emitTurnStart();+ await act(async () => {+ streamCalls[0]!.onMessage({+ type: "workflow_draft",+ block_labels: [],+ workflow: staged,+ });+ if (options.errorFrame) {+ streamCalls[0]!.onMessage({+ type: "error",+ turn_id: turnId,+ error: "The stream ended while saving the workflow.",+ });+ streamCalls[0]!.resolve();+ }+ await Promise.resolve();+ });+ vi.useFakeTimers();+ if (remount !== "mid-stream" && !options.errorFrame)+ await closeStreamWithoutTerminal();+ if (remount !== "none") {+ view.unmount();+ await act(async () => {+ render(chatUi(props));+ });+ await resolveNextHistory({+ ...historyData(),+ chat_history: capturedHistory.chat_history.slice(0, -1),+ });+ }+ await advance(2_000);+ await resolveNextHistory({+ ...recoveredHistory(undefined, options.terminalReason),+ request_turn_id: turnId,+ proposed_workflow: staged,+ proposed_workflow_metadata: {+ owner_turn_id: turnId,+ revision: 1,+ canonical_fingerprint: "canonical-1",+ disposition: "review_untested",+ workflow_run_id: null,+ },+ });+ await act(async () => {+ await Promise.resolve();+ });+ expect(useWorkflowYamlEditorStore.getState().copilotAcceptance).toBeNull();+ return restore;+ }++ it.each([+ ["mid-stream", null],+ ["after the drop", null],+ ["none", null],+ ["none", "verified_goal_satisfied"],+ ["mid-stream", "verified_goal_satisfied"],+ ["none", "timeout"],+ ["mid-stream", "timeout"],+ ["none", "turn_halt:browser_session_lost"],+ ["mid-stream", "turn_halt:browser_session_lost"],+ ] as const)(+ "keeps a recovered turn's staged proposal and canvas (remount: %s, terminal_reason: %s)",+ async (remount, terminalReason) => {+ const restore = await recoverStagedTurn(remount, {+ terminalReason: terminalReason ?? undefined,+ });++ expect(restore).not.toHaveBeenCalled();+ const accept = screen.getByRole("button", { name: "Accept" });+ expect(accept.hasAttribute("disabled")).toBe(false);+ },+ );++ it.each(["cancelled", "copilot_recoverable_failure", "user_cancelled"])(+ "still rolls back a turn recovered after a remount whose terminal_reason is %s",+ async (terminalReason) => {+ const restore = await recoverStagedTurn("mid-stream", { terminalReason });++ expect(restore).toHaveBeenCalledOnce();+ },+ );++ it("still rolls back a staged turn whose error frame arrived before the pane remounted", async () => {+ const restore = await recoverStagedTurn("mid-stream", { errorFrame: true });++ expect(restore).toHaveBeenCalledOnce();+ });+it("keeps Reject reserved when a pre-cancellation canonical read returns before the turn is identified", async () => {const canonical = {workflow_id: "wf_1",diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsxindex 50ebb3b7e..1677996c3 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx@@ -514,7 +514,7 @@ function finishTurnHistory() {{sender: "ai",content: "Turn finished",- turn_outcome: { copilot_turn_id: "turn-1", terminal_reason: "completed" },+ turn_outcome: { copilot_turn_id: "turn-1", terminal_reason: null },},];}@@ -851,7 +851,7 @@ function completedHistory() {created_at: new Date().toISOString(),turn_outcome: {copilot_turn_id: "turn-recovered",- terminal_reason: "completed",+ terminal_reason: null,request_cancel_token: "original-cancel-token",},},@@ -1952,7 +1952,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {created_at: new Date().toISOString(),turn_outcome: {copilot_turn_id: "turn-accepted",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -2053,7 +2053,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {created_at: new Date().toISOString(),turn_outcome: {copilot_turn_id: "turn-resumed",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -2156,7 +2156,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {expect(screen.queryByRole("button", { name: "Accept" })).toBeNull();});- it.each(["user_cancelled", "copilot_recoverable_failure", "completed"])(+ it.each(["user_cancelled", "copilot_recoverable_failure", null])("reconciles the pre-turn canvas after recovered %s with unchanged canonical",async (terminal) => {changesState.hasChanges = true;@@ -2223,7 +2223,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {},];await act(async () => vi.advanceTimersByTimeAsync(2_000));- if (terminal === "completed") expect(apply).not.toHaveBeenCalled();+ if (terminal === null) expect(apply).not.toHaveBeenCalled();elseexpect(apply).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({@@ -2294,7 +2294,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Finished",turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: action === "Reject" ? "cancelled" : "completed",+ terminal_reason: action === "Reject" ? "cancelled" : null,},},];@@ -2360,7 +2360,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Saved",turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -3009,7 +3009,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {created_at: "2026-09-11T00:00:00Z",turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -3097,7 +3097,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {created_at: new Date().toISOString(),turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -3299,7 +3299,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Other turn",turn_outcome: {copilot_turn_id: "turn-other",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -3345,7 +3345,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Final commit saved",turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -3424,7 +3424,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Final commit saved",turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -3513,7 +3513,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Final commit saved",turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -3771,7 +3771,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {created_at: new Date().toISOString(),turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -9852,7 +9852,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {created_at: "2026-09-11T00:00:00Z",turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -9965,7 +9965,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {created_at: "2026-09-11T00:00:02Z",turn_outcome: {copilot_turn_id: "turn-other",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -10243,7 +10243,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {);it.each(["updated", "unchanged", "interrupted"] as const)(- "resumes recovery after workflow navigation and asks before replacing local edits (%s canonical outcome)",+ "resumes recovery after workflow navigation without losing local edits (%s canonical outcome)",async (outcome) => {changesState.hasChanges = true;saveData.workflow.workflow_definition = {@@ -10336,22 +10336,25 @@ describe("WorkflowCopilotChat — g2 review gate", () => {});}expect(revisitedApply).not.toHaveBeenCalled();- expect(- screen.getByRole("button", { name: "Keep my edits" }),- ).toBeTruthy();const generation =useWorkflowHasChangesStore.getState().saveGeneration;- await act(async () => {- fireEvent.click(- screen.getByRole("button", {- name:- outcome === "updated"- ? "Apply and discard my edits"- : "Keep my edits",- }),- );- await vi.advanceTimersByTimeAsync(2_000);- });+ if (outcome === "updated") {+ expect(+ screen.getByRole("button", { name: "Keep my edits" }),+ ).toBeTruthy();+ await act(async () => {+ fireEvent.click(+ screen.getByRole("button", {+ name: "Apply and discard my edits",+ }),+ );+ await vi.advanceTimersByTimeAsync(2_000);+ });+ } else {+ expect(+ screen.queryByRole("button", { name: "Keep my edits" }),+ ).toBeNull();+ }if (outcome === "updated") {expect(revisitedApply).toHaveBeenCalledExactlyOnceWith(saved.current,@@ -10684,7 +10687,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Another tab finished",turn_outcome: {copilot_turn_id: "another-turn",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -10858,7 +10861,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Final commit saved",turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -10974,7 +10977,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Final commit saved",turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -11327,7 +11330,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {created_at: new Date().toISOString(),turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -11432,7 +11435,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Other turn",turn_outcome: {copilot_turn_id: "turn-other",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -11474,7 +11477,7 @@ describe("WorkflowCopilotChat — g2 review gate", () => {content: "Final commit saved",turn_outcome: {copilot_turn_id: "turn-1",- terminal_reason: "completed",+ terminal_reason: null,},},];@@ -12891,9 +12894,9 @@ it("A46 describes a cleared proposal as a changed saved workflow without attribu});describe("editor-state rollback lifecycle", () => {- it.each(["none", "keep", "discard"] as const)(- "settles an unchanged parked turn without claiming a save (local edit choice=%s)",- async (choice) => {+ it.each([false, true])(+ "settles an unchanged parked turn without claiming a save (local edits=%s)",+ async (localEdits) => {saveData.workflow = {...saveData.workflow,title: saveData.title,@@ -12925,7 +12928,7 @@ describe("editor-state rollback lifecycle", () => {onWorkflowUpdate: apply,onRestore: restore,beforeRecovery: () => {- if (choice === "none") return;+ if (!localEdits) return;expect(refuseMutationDuringYamlCommit()).toBe(false);editorNodes = editorNodes.map((node) =>node.id === "loop"@@ -12944,35 +12947,16 @@ describe("editor-state rollback lifecycle", () => {fireEvent.click(screen.getByRole("button", { name: "Retry" }));await vi.advanceTimersByTimeAsync(2_000);});- if (choice !== "none") {+ if (localEdits) {expect(editorNodes.find((node) => node.id === "loop")?.data,).toMatchObject({ loopValue: "fresh_local_items" });expect(restore).not.toHaveBeenCalled();expect(apply).not.toHaveBeenCalled();expect(- screen.getByRole("button", { name: "Keep my edits" }),- ).toBeTruthy();- await act(async () => {- fireEvent.click(- screen.getByRole("button", {- name:- choice === "keep"- ? "Keep my edits"- : "Apply and discard my edits",- }),- );- await vi.advanceTimersByTimeAsync(2_000);- });- if (choice === "keep") {- expect(- editorNodes.find((node) => node.id === "loop")?.data,- ).toMatchObject({ loopValue: "fresh_local_items" });- expect(useWorkflowHasChangesStore.getState().hasChanges).toBe(true);- } else- expect(- editorNodes.find((node) => node.id === "loop"),- ).toBeUndefined();+ screen.queryByRole("button", { name: "Keep my edits" }),+ ).toBeNull();+ expect(useWorkflowHasChangesStore.getState().hasChanges).toBe(true);}expect(parked.rollback?.workflowPersisted).toBe(false);expect(useWorkflowHasChangesStore.getState().saveGeneration).toBe(diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex 00c8e0c12..5dee33f63 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -3773,18 +3773,18 @@ export function WorkflowCopilotChat({const reason = row.turn_outcome?.terminal_reason;if (canonicalRecovery?.awaitingTurnId &&- canonicalRecovery.awaitingTurnId === rowTurnId &&- reason+ canonicalRecovery.awaitingTurnId === rowTurnId) {canonicalRecovery.terminalConfirmed = true;canonicalRecovery.restoreRollback ||=isCancelledRefinementTurn(reason, narrative) ||narrative?.terminal === "error" ||- [- "cancelled",- "error",- "copilot_recoverable_failure",- ].includes(reason);+ (!!reason &&+ [+ "cancelled",+ "error",+ "copilot_recoverable_failure",+ ].includes(reason));canonicalReadAttempted = true;await reconcileCanonicalWorkflowRef.current?.(reservation,@@ -6146,7 +6146,6 @@ export function WorkflowCopilotChat({useWorkflowHasChangesStore.getState().hasChanges ||(state.active &&(state.stale || state.draft !== state.entrySnapshot)),- restoreRollback: true,});startRecoveryPoll(parked.poll?.chatId ?? null,@@ -6852,7 +6851,6 @@ export function WorkflowCopilotChat({awaitingTurnId: streamTurnId ?? undefined,terminalConfirmed: false,rollback: submittedSnapshot ?? undefined,- restoreRollback: true,preservedSettings: submittedSettings,waitingForUnlock: false,yaml: yaml.activediff --git a/skyvern-frontend/src/routes/workflows/editor/browserBlockUrl.test.ts b/skyvern-frontend/src/routes/workflows/editor/browserBlockUrl.test.tsnew file mode 100644index 000000000..6e055ec01--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/browserBlockUrl.test.ts@@ -0,0 +1,193 @@+import type { Edge } from "@xyflow/react";+import { describe, expect, test } from "vitest";++import { RunEngine } from "@/api/types";++import { getBrowserBlockUrlError } from "./browserBlockUrl";+import type { AppNode } from "./nodes";+import {+ conditionalNodeDefaultData,+ createBranchCondition,+} from "./nodes/ConditionalNode/types";+import { loopNodeDefaultData } from "./nodes/LoopNode/types";+import {+ navigationNodeDefaultData,+ type NavigationNodeData,+} from "./nodes/NavigationNode/types";+import { urlNodeDefaultData } from "./nodes/URLNode/types";+import { isMissingRequiredStartUrl } from "./workflowEditorUtils";++const start = {+ id: "start",+ type: "start",+ position: { x: 0, y: 0 },+ data: {},+} as AppNode;++function navigation(+ id: string,+ overrides: Partial<NavigationNodeData> = {},+ parentId?: string,+): AppNode {+ return {+ id,+ type: "navigation",+ position: { x: 0, y: 0 },+ parentId,+ data: { ...navigationNodeDefaultData, label: id, ...overrides },+ } as AppNode;+}++function edge(source: string, target: string): Edge {+ return { id: `${source}-${target}`, source, target };+}++describe("isMissingRequiredStartUrl", () => {+ test("flags only an empty URL on the block that opens the first page", () => {+ const nodes = [start, navigation("first"), navigation("second")];+ const edges = [edge("start", "first"), edge("first", "second")];++ expect(isMissingRequiredStartUrl(nodes, edges, "first")).toBe(true);+ expect(isMissingRequiredStartUrl(nodes, edges, "second")).toBe(false);++ const withUrl = [+ start,+ navigation("first", { url: "https://example.com" }),+ navigation("second"),+ ];+ expect(isMissingRequiredStartUrl(withUrl, edges, "first")).toBe(false);+ });++ test("a 2.0 block derives its own URL and does not open a page for later blocks", () => {+ const nodes = [+ start,+ navigation("v2", { engine: RunEngine.SkyvernV2 }),+ navigation("v1"),+ ];+ const edges = [edge("start", "v2"), edge("v2", "v1")];++ expect(isMissingRequiredStartUrl(nodes, edges, "v2")).toBe(false);+ expect(isMissingRequiredStartUrl(nodes, edges, "v1")).toBe(true);+ });++ test("a block inside a loop is covered by a browser block before the loop", () => {+ const loop = {+ id: "loop",+ type: "loop",+ position: { x: 0, y: 0 },+ data: { ...loopNodeDefaultData, label: "loop" },+ } as AppNode;+ const nodes = [+ start,+ navigation("before"),+ loop,+ navigation("inner", {}, "loop"),+ ];+ const edges = [edge("start", "before"), edge("before", "loop")];++ expect(isMissingRequiredStartUrl(nodes, edges, "inner")).toBe(false);+ });+});++describe("isMissingRequiredStartUrl across block types and branches", () => {+ test("an empty first Go to URL block needs a URL", () => {+ const goto = {+ id: "goto",+ type: "url",+ position: { x: 0, y: 0 },+ data: { ...urlNodeDefaultData, label: "goto" },+ } as AppNode;++ expect(+ isMissingRequiredStartUrl([start, goto], [edge("start", "goto")], "goto"),+ ).toBe(true);+ });++ test("a conditional opens a page for later blocks only when every branch does", () => {+ const branch = createBranchCondition({ id: "branch" });+ const fallback = createBranchCondition({+ id: "fallback",+ is_default: true,+ });+ const conditional = {+ id: "cond",+ type: "conditional",+ position: { x: 0, y: 0 },+ data: {+ ...conditionalNodeDefaultData,+ label: "cond",+ branches: [branch, fallback],+ },+ } as AppNode;+ const inBranch = (id: string, branchId: string) =>+ ({+ ...navigation(id, { url: "https://example.com" }, "cond"),+ data: {+ ...navigationNodeDefaultData,+ label: id,+ url: "https://example.com",+ conditionalBranchId: branchId,+ },+ }) as AppNode;+ const edges = [edge("start", "cond"), edge("cond", "after")];++ const oneBranchOpensPage = [+ start,+ conditional,+ inBranch("a", "branch"),+ navigation("after"),+ ];+ expect(isMissingRequiredStartUrl(oneBranchOpensPage, edges, "after")).toBe(+ true,+ );++ const bothBranchesOpenPage = [+ ...oneBranchOpensPage,+ inBranch("b", "fallback"),+ ];+ expect(+ isMissingRequiredStartUrl(bothBranchesOpenPage, edges, "after"),+ ).toBe(false);+ });+});++describe("getBrowserBlockUrlError", () => {+ test.each([+ "https://example.com",+ "example.com/path?q=1",+ "http://localhost:3000/login",+ "http://internal-service:8080",+ "sub.example.co.uk",+ "192.168.1.10:8080",+ "münchen.de",+ "{{ starting_url }}",+ "https://{{ host }}/login",+ "",+ ])("accepts %j", (url) => {+ expect(getBrowserBlockUrlError(url)).toBeNull();+ });++ test.each([+ "example",+ "example.",+ "https://example.",+ "example..com",+ "example.c",+ "10",+ "ftp://example.com",+ "javascript:alert(1)",+ "https://",+ ])("rejects %j", (url) => {+ expect(getBrowserBlockUrlError(url)).not.toBeNull();+ });++ // The backend's urlparse reads "example.com:8080" as a scheme and rejects it,+ // so a scheme-less host:port must point the user at the fix, not look valid.+ test.each([+ ["example.com:8080", /https:\/\//],+ ["localhost:3000/login", /https:\/\//],+ ["ftp://example.com", /http:\/\/ and https:\/\//],+ ])("explains why %j is refused", (url, message) => {+ expect(getBrowserBlockUrlError(url)).toMatch(message);+ });+});diff --git a/skyvern-frontend/src/routes/workflows/editor/browserBlockUrl.ts b/skyvern-frontend/src/routes/workflows/editor/browserBlockUrl.tsnew file mode 100644index 000000000..fe21c956a--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/browserBlockUrl.ts@@ -0,0 +1,72 @@+import { isTemplateExpression } from "@/util/googleSheetsUrl";++import type { AppNode } from "./nodes";++const INVALID_URL_MESSAGE = "Enter a full web address, like example.com.";+const HOST_PORT_MESSAGE =+ "Add https:// before an address with a port, like https://example.com:8080.";+const UNSUPPORTED_SCHEME_MESSAGE =+ "Only http:// and https:// addresses can be opened.";++const IPV4_HOST = /^\d{1,3}(\.\d{1,3}){3}$/;+// The URL parser has already lowercased and punycoded the host.+const TOP_LEVEL_DOMAIN = /^([a-z]{2,63}|xn--[a-z0-9-]{1,59})$/;++function isPlausibleHost(host: string, typed: string, hasScheme: boolean) {+ if (host.startsWith("[")) return true;+ // The URL parser turns bare numbers into IPv4 ("10" becomes "0.0.0.10"), so+ // only trust an IPv4 host that was typed out in full.+ if (IPV4_HOST.test(host)) return typed.includes(host);+ if (!host.includes(".")) {+ // A bare word like "example" is a typo; an explicit http://service:port+ // stays valid for self-hosted setups.+ return host === "localhost" || hasScheme;+ }+ const labels = host.split(".");+ return (+ labels.every((label) => label !== "") &&+ TOP_LEVEL_DOMAIN.test(labels[labels.length - 1]!)+ );+}++// The backend prepends https:// to a scheme-less URL and only accepts http(s)+// (url_validators._prepend_scheme), so match that before judging the host.+export function getBrowserBlockUrlError(url: string): string | null {+ const trimmed = url.trim();+ if (trimmed === "" || isTemplateExpression(trimmed)) return null;++ const scheme = trimmed.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/)?.[1];+ if (scheme && !["http", "https"].includes(scheme.toLowerCase())) {+ // Python's urlparse reads "example.com:8080" as scheme "example.com", so the+ // backend rejects a host:port with no scheme too; say how to fix it.+ return /^[^:]+:\d+(\/|$)/.test(trimmed)+ ? HOST_PORT_MESSAGE+ : UNSUPPORTED_SCHEME_MESSAGE;+ }++ let parsed: URL;+ try {+ parsed = new URL(scheme ? trimmed : `https://${trimmed}`);+ } catch {+ return INVALID_URL_MESSAGE;+ }++ return isPlausibleHost(parsed.hostname, trimmed.toLowerCase(), !!scheme)+ ? null+ : INVALID_URL_MESSAGE;+}++// File Download is left out: its URL can also be a bare Google Drive file id.+export function getNodeBrowserUrlError(node: AppNode): string | null {+ switch (node.type) {+ case "task":+ case "navigation":+ case "action":+ case "extraction":+ case "login":+ case "url":+ return getBrowserBlockUrlError(node.data.url);+ default:+ return null;+ }+}diff --git a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts b/skyvern-frontend/src/routes/workflows/editor/helpContent.tsindex f11df1c87..6d6a2f02e 100644--- a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts+++ b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts@@ -44,6 +44,10 @@ export const basePlaceholderContent = {totpIdentifier: "Add an ID that links your TOTP to the block",};+// The run's browser starts on about:blank, so the first browser block must navigate somewhere.+export const firstBrowserBlockUrlPlaceholder =+ "(required) Navigate to this URL: https://...";+export const helpTooltips = {task: baseHelpTooltipContent,taskv2: {diff --git a/skyvern-frontend/src/routes/workflows/editor/hooks/useBlockUrlError.ts b/skyvern-frontend/src/routes/workflows/editor/hooks/useBlockUrlError.tsnew file mode 100644index 000000000..5f69addd5--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/hooks/useBlockUrlError.ts@@ -0,0 +1,37 @@+import { useEdges, useNodes } from "@xyflow/react";+import { useEffect } from "react";++import { useMissingStartUrlStore } from "@/store/MissingStartUrlStore";++import { getNodeBrowserUrlError } from "../browserBlockUrl";+import type { AppNode } from "../nodes";+import { isMissingRequiredStartUrl } from "../workflowEditorUtils";++const MISSING_START_URL_MESSAGE =+ "Add a URL. No earlier block opens a page, so this block would start on a blank page.";++function blockUrlErrorId(blockId: string): string {+ return `${blockId}-url-error`;+}++function useBlockUrlError(blockId: string): string | null {+ const nodes = useNodes<AppNode>();+ const edges = useEdges();+ const flagged = useMissingStartUrlStore((state) =>+ state.flaggedBlockIds.has(blockId),+ );+ const clear = useMissingStartUrlStore((state) => state.clear);+ const missing = isMissingRequiredStartUrl(nodes, edges, blockId);++ // Re-derived from the graph, so the flag also drops when an earlier+ // page-opening block is added, not only when a URL is typed.+ useEffect(() => {+ if (flagged && !missing) clear(blockId);+ }, [flagged, missing, clear, blockId]);++ if (flagged && missing) return MISSING_START_URL_MESSAGE;+ const node = nodes.find((node) => node.id === blockId);+ return node ? getNodeBrowserUrlError(node) : null;+}++export { blockUrlErrorId, useBlockUrlError };diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/ActionNode/ActionEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/ActionNode/ActionEditor.tsxindex f569fc524..5473d48cc 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/ActionNode/ActionEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/ActionNode/ActionEditor.tsx@@ -18,7 +18,11 @@ import { WorkflowBlockInputTextarea } from "@/components/WorkflowBlockInputTextaimport { ErrorCodeMappingEditor } from "@/routes/workflows/editor/ErrorCodeMappingEditor";import { AI_IMPROVE_CONFIGS } from "../../constants";-import { helpTooltips, placeholders } from "../../helpContent";+import {+ firstBrowserBlockUrlPlaceholder,+ helpTooltips,+ placeholders,+} from "../../helpContent";import { useIsFirstBlockInWorkflow } from "../../hooks/useIsFirstNodeInWorkflow";import { useHasInteractedThisSession } from "../../panels/useHasInteractedThisSession";import { BlockExecutionOptions } from "../components/BlockExecutionOptions";@@ -29,10 +33,16 @@ import { ParametersMultiSelect } from "../TaskNode/ParametersMultiSelect";import { errorMappingExampleValue } from "../types";import { type AppNode } from "..";import { ActionNode, ActionNodeData } from "./types";+import { cn } from "@/util/utils";+import {+ blockUrlErrorId,+ useBlockUrlError,+} from "../../hooks/useBlockUrlError";import { useUpdate } from "../../useUpdate";import {getAvailableOutputParameterKeys,getParentLoopSkipsOnFail,+ isFirstBrowserTaskBlock,isNodeInsideForLoop,} from "../../workflowEditorUtils";@@ -71,6 +81,10 @@ function ActionEditorBody({const update = useUpdate<ActionNodeData>({ id: blockId, editable });const nodes = useNodes<AppNode>();const edges = useEdges();+ const urlPlaceholder = isFirstBrowserTaskBlock(nodes, edges, blockId)+ ? firstBrowserBlockUrlPlaceholder+ : placeholders["action"]["url"];+ const urlError = useBlockUrlError(blockId);const outputParameterKeys = getAvailableOutputParameterKeys(nodes,edges,@@ -103,9 +117,19 @@ function ActionEditorBody({nodeId={blockId}onChange={(value) => update({ url: value })}value={data.url}- placeholder={placeholders["action"]["url"]}- className="nopan text-xs"+ placeholder={urlPlaceholder}+ aria-invalid={urlError !== null}+ aria-describedby={urlError ? blockUrlErrorId(blockId) : undefined}+ className={cn(+ "nopan text-xs",+ urlError !== null && "border-destructive",+ )}/>+ {urlError ? (+ <p id={blockUrlErrorId(blockId)} className="text-xs text-destructive">+ {urlError}+ </p>+ ) : null}</div><div className="space-y-2"><div className="flex gap-2">diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsxindex dc5cd3a58..8579e9d6f 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsx@@ -26,6 +26,7 @@ import {import { Separator } from "@/components/ui/separator";import { Switch } from "@/components/ui/switch";import { GOOGLE_DRIVE_REQUIRED_SCOPES } from "@/util/googleScopes";+import { cn } from "@/util/utils";import { ErrorCodeMappingEditor } from "../../ErrorCodeMappingEditor";import { AI_IMPROVE_CONFIGS } from "../../constants";@@ -37,6 +38,10 @@ import { IgnoreWorkflowSystemPrompt } from "../IgnoreWorkflowSystemPrompt";import { BlockExecutionOptions } from "../components/BlockExecutionOptions";import { type FileDownloadNode, type FileDownloadNodeData } from "./types";import { useSelectedCredentialTotpIdentifier } from "../../hooks/useSelectedCredentialTotpIdentifier";+import {+ blockUrlErrorId,+ useBlockUrlError,+} from "../../hooks/useBlockUrlError";import { errorMappingExampleValue } from "../types";import { ParametersMultiSelect } from "../TaskNode/ParametersMultiSelect";import { useUpdate } from "../../useUpdate";@@ -139,6 +144,7 @@ function FileDownloadEditorBody({blockId,);const isFirstBrowserTask = isFirstBrowserTaskBlock(nodes, edges, blockId);+ const urlError = useBlockUrlError(blockId);const isInsideForLoop = isNodeInsideForLoop(nodes, blockId);const parentLoopSkipsOnFail = getParentLoopSkipsOnFail(nodes, blockId);const update = useUpdate<FileDownloadNodeData>({ id: blockId, editable });@@ -167,12 +173,27 @@ function FileDownloadEditorBody({onChange={(next) => update({ url: next })}value={url}placeholder={urlPlaceholder}- className="nopan text-xs"+ aria-invalid={urlError !== null}+ aria-describedby={urlError ? blockUrlErrorId(blockId) : undefined}+ className={cn(+ "nopan text-xs",+ urlError !== null && "border-destructive",+ )}/>- {isFirstBrowserTask && !url.trim() && (- <p className="text-xs text-amber-700 dark:text-amber-400">- Nothing runs before this block, so it needs a URL to start from.+ {urlError ? (+ <p+ id={blockUrlErrorId(blockId)}+ className="text-xs text-destructive"+ >+ {urlError}</p>+ ) : (+ isFirstBrowserTask &&+ !url.trim() && (+ <p className="text-xs text-amber-700 dark:text-amber-400">+ Nothing runs before this block, so it needs a URL to start from.+ </p>+ ))}</div><div className="space-y-2">diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsxindex b8ec5d021..bfc350525 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsx@@ -28,7 +28,11 @@ import { useWorkflowParametersStore } from "@/store/WorkflowParametersStore";import { ErrorCodeMappingEditor } from "../../ErrorCodeMappingEditor";import { AI_IMPROVE_CONFIGS } from "../../constants";-import { helpTooltips, placeholders } from "../../helpContent";+import {+ firstBrowserBlockUrlPlaceholder,+ helpTooltips,+ placeholders,+} from "../../helpContent";import { useIsFirstBlockInWorkflow } from "../../hooks/useIsFirstNodeInWorkflow";import { type AppNode } from "..";import { parameterIsSkyvernCredential } from "../../types";@@ -40,10 +44,16 @@ import { useSelectedCredentialTotpIdentifier } from "../../hooks/useSelectedCredimport { type LoginNode, type LoginNodeData } from "./types";import { errorMappingExampleValue } from "../types";import { ParametersMultiSelect } from "../TaskNode/ParametersMultiSelect";+import { cn } from "@/util/utils";+import {+ blockUrlErrorId,+ useBlockUrlError,+} from "../../hooks/useBlockUrlError";import { useUpdate } from "../../useUpdate";import {getAvailableOutputParameterKeys,getParentLoopSkipsOnFail,+ isFirstBrowserTaskBlock,isNodeInsideForLoop,} from "../../workflowEditorUtils";@@ -80,6 +90,10 @@ function LoginEditorBody({const update = useUpdate<LoginNodeData>({ id: blockId, editable });const nodes = useNodes<AppNode>();const edges = useEdges();+ const urlPlaceholder = isFirstBrowserTaskBlock(nodes, edges, blockId)+ ? firstBrowserBlockUrlPlaceholder+ : placeholders["login"]["url"];+ const urlError = useBlockUrlError(blockId);const outputParameterKeys = getAvailableOutputParameterKeys(nodes,edges,@@ -139,9 +153,19 @@ function LoginEditorBody({nodeId={blockId}onChange={(value) => update({ url: value })}value={data.url}- placeholder={placeholders["login"]["url"]}- className="nopan text-xs"+ placeholder={urlPlaceholder}+ aria-invalid={urlError !== null}+ aria-describedby={urlError ? blockUrlErrorId(blockId) : undefined}+ className={cn(+ "nopan text-xs",+ urlError !== null && "border-destructive",+ )}/>+ {urlError ? (+ <p id={blockUrlErrorId(blockId)} className="text-xs text-destructive">+ {urlError}+ </p>+ ) : null}</div><div className="space-y-2"><div className="flex gap-2">diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.test.tsxindex bf1e6be4a..3139e42b6 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.test.tsx@@ -87,6 +87,8 @@ vi.mock("../../panels/useHasInteractedThisSession", () => ({vi.mock("../../workflowEditorUtils", () => ({getAvailableOutputParameterKeys: () => [],getParentLoopSkipsOnFail: () => false,+ isFirstBrowserTaskBlock: () => false,+ isMissingRequiredStartUrl: () => false,isNodeInsideForLoop: () => false,}));diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.tsxindex 1af675a69..fb5cf5bae 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.tsx@@ -19,7 +19,11 @@ import { Switch } from "@/components/ui/switch";import { ErrorCodeMappingEditor } from "@/routes/workflows/editor/ErrorCodeMappingEditor";import { AI_IMPROVE_CONFIGS } from "../../constants";-import { helpTooltips, placeholders } from "../../helpContent";+import {+ firstBrowserBlockUrlPlaceholder,+ helpTooltips,+ placeholders,+} from "../../helpContent";import { useHasInteractedThisSession } from "../../panels/useHasInteractedThisSession";import { type AppNode } from "..";import { DisableCache } from "../DisableCache";@@ -33,10 +37,16 @@ import {} from "./types";import { ParametersMultiSelect } from "../TaskNode/ParametersMultiSelect";import { errorMappingExampleValue } from "../types";+import { cn } from "@/util/utils";+import {+ blockUrlErrorId,+ useBlockUrlError,+} from "../../hooks/useBlockUrlError";import { useUpdate } from "../../useUpdate";import {getAvailableOutputParameterKeys,getParentLoopSkipsOnFail,+ isFirstBrowserTaskBlock,isNodeInsideForLoop,} from "../../workflowEditorUtils";@@ -63,6 +73,10 @@ function NavigationEditorBody({const update = useUpdate<NavigationNodeData>({ id: blockId, editable });const nodes = useNodes<AppNode>();const edges = useEdges();+ const urlPlaceholder = isFirstBrowserTaskBlock(nodes, edges, blockId)+ ? firstBrowserBlockUrlPlaceholder+ : placeholders["navigation"]["url"];+ const urlError = useBlockUrlError(blockId);const outputParameterKeys = getAvailableOutputParameterKeys(nodes,edges,@@ -276,9 +290,22 @@ function NavigationEditorBody({nodeId={blockId}onChange={(value) => update({ url: value })}value={data.url}- placeholder={placeholders["navigation"]["url"]}- className="nopan text-xs"+ placeholder={urlPlaceholder}+ aria-invalid={urlError !== null}+ aria-describedby={urlError ? blockUrlErrorId(blockId) : undefined}+ className={cn(+ "nopan text-xs",+ urlError !== null && "border-destructive",+ )}/>+ {urlError ? (+ <p+ id={blockUrlErrorId(blockId)}+ className="text-xs text-destructive"+ >+ {urlError}+ </p>+ ) : null}</div><div className="space-y-2"><div className="flex gap-2">diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/TaskNode/TaskEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/TaskNode/TaskEditor.tsxindex 1b57b4f43..58bf3a548 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/TaskNode/TaskEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/TaskNode/TaskEditor.tsx@@ -20,7 +20,11 @@ import { ModelSelector } from "@/components/ModelSelector";import { ErrorCodeMappingEditor } from "@/routes/workflows/editor/ErrorCodeMappingEditor";import { AI_IMPROVE_CONFIGS } from "../../constants";-import { helpTooltips, placeholders } from "../../helpContent";+import {+ firstBrowserBlockUrlPlaceholder,+ helpTooltips,+ placeholders,+} from "../../helpContent";import { useIsFirstBlockInWorkflow } from "../../hooks/useIsFirstNodeInWorkflow";import { useHasInteractedThisSession } from "../../panels/useHasInteractedThisSession";import { type AppNode, isWorkflowBlockNode } from "..";@@ -31,10 +35,16 @@ import { useSelectedCredentialTotpIdentifier } from "../../hooks/useSelectedCredimport { ParametersMultiSelect } from "./ParametersMultiSelect";import type { TaskNode, TaskNodeData } from "./types";import { dataSchemaExampleValue, errorMappingExampleValue } from "../types";+import { cn } from "@/util/utils";+import {+ blockUrlErrorId,+ useBlockUrlError,+} from "../../hooks/useBlockUrlError";import { useUpdate } from "../../useUpdate";import {getAvailableOutputParameterKeys,getParentLoopSkipsOnFail,+ isFirstBrowserTaskBlock,isNodeInsideForLoop,} from "../../workflowEditorUtils";@@ -51,6 +61,9 @@ function TaskEditorBody({ blockId }: { blockId: string }) {];const nodes = useNodes<AppNode>();const edges = useEdges();+ const urlPlaceholder = isFirstBrowserTaskBlock(nodes, edges, blockId)+ ? firstBrowserBlockUrlPlaceholder+ : placeholders["task"]["url"];// Subscribe to the node via the live useNodes() store rather than a// snapshot from reactFlowInstance.getNode - sidebar editors mount via// BlockConfigForm (not the RF node renderer), so a getNode snapshot@@ -70,6 +83,7 @@ function TaskEditorBody({ blockId }: { blockId: string }) {blockId,);const isFirstWorkflowBlock = useIsFirstBlockInWorkflow({ id: blockId });+ const urlError = useBlockUrlError(blockId);const isInsideForLoop = isNodeInsideForLoop(nodes, blockId);const parentLoopSkipsOnFail = getParentLoopSkipsOnFail(nodes, blockId);const hasInteracted = useHasInteractedThisSession();@@ -110,9 +124,24 @@ function TaskEditorBody({ blockId }: { blockId: string }) {nodeId={blockId}onChange={(value) => update({ url: value })}value={data.url}- placeholder={placeholders["task"]["url"]}- className="nopan text-xs"+ placeholder={urlPlaceholder}+ aria-invalid={urlError !== null}+ aria-describedby={+ urlError ? blockUrlErrorId(blockId) : undefined+ }+ className={cn(+ "nopan text-xs",+ urlError !== null && "border-destructive",+ )}/>+ {urlError ? (+ <p+ id={blockUrlErrorId(blockId)}+ className="text-xs text-destructive"+ >+ {urlError}+ </p>+ ) : null}</div><div className="space-y-2"><div className="flex gap-2">diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/URLNode/URLEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/URLNode/URLEditor.tsxindex 35dfd9d2f..621e7a905 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/URLNode/URLEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/URLNode/URLEditor.tsx@@ -3,7 +3,13 @@ import { useReactFlow } from "@xyflow/react";import { Label } from "@/components/ui/label";import { WorkflowBlockInputTextarea } from "@/components/WorkflowBlockInputTextarea";+import { cn } from "@/util/utils";+import { placeholders } from "../../helpContent";+import {+ blockUrlErrorId,+ useBlockUrlError,+} from "../../hooks/useBlockUrlError";import { type AppNode, isWorkflowBlockNode } from "..";import { isUrlNode } from "./types";import { useUpdate } from "../../useUpdate";@@ -33,6 +39,7 @@ function URLEditorBody({editable: boolean;}) {const update = useUpdate<{ url: string }>({ id: blockId, editable });+ const urlError = useBlockUrlError(blockId);return (<div data-testid="url-block-form" className="space-y-4">@@ -44,8 +51,18 @@ function URLEditorBody({onChange={(next) => update({ url: next })}value={url}placeholder={placeholders["url"]["url"]}- className="nopan text-xs"+ aria-invalid={urlError !== null}+ aria-describedby={urlError ? blockUrlErrorId(blockId) : undefined}+ className={cn(+ "nopan text-xs",+ urlError !== null && "border-destructive",+ )}/>+ {urlError ? (+ <p id={blockUrlErrorId(blockId)} className="text-xs text-destructive">+ {urlError}+ </p>+ ) : null}</div></div>);diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsxindex 0f36d23f6..743e94950 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx@@ -74,6 +74,7 @@ import { getInitialValues } from "@/routes/workflows/utils";import { useDebuggerLastRunValuesStore } from "@/store/DebuggerLastRunValuesStore";import { useBlockOutputStore } from "@/store/BlockOutputStore";import { useDebugStore } from "@/store/useDebugStore";+import { useMissingStartUrlStore } from "@/store/MissingStartUrlStore";import {RUN_APPEND_PANES,withPanesOpen,@@ -104,7 +105,11 @@ import { workflowBlockTitle } from "../types";import { MicroDropdown } from "./MicroDropdown";import { BlockParametersDialog } from "./BlockParametersDialog";import type { AppNode } from "..";-import { getWorkflowErrors } from "../../workflowEditorUtils";+import {+ getWorkflowErrors,+ isMissingRequiredStartUrl,+} from "../../workflowEditorUtils";+import { getNodeBrowserUrlError } from "../../browserBlockUrl";import { NodeGripHandle } from "./NodeGripHandle";import {getDragGateReason,@@ -405,6 +410,23 @@ function NodeHeader({const allErrors = getWorkflowErrors(reactFlow.getNodes());const labelPrefix = `${blockLabel}:`;const blockErrors = allErrors.filter((e) => e.startsWith(labelPrefix));+ if (+ isMissingRequiredStartUrl(+ reactFlow.getNodes(),+ reactFlow.getEdges(),+ nodeId,+ )+ ) {+ useMissingStartUrlStore.getState().flag(nodeId);+ blockErrors.push(+ `${blockLabel}: URL is required. No earlier block opens a page, so the run would start on a blank page.`,+ );+ }+ const thisNode = reactFlow.getNode(nodeId) as AppNode | undefined;+ const urlError = thisNode ? getNodeBrowserUrlError(thisNode) : null;+ if (urlError) {+ blockErrors.push(`${blockLabel}: ${urlError}`);+ }if (blockErrors.length > 0) {toast({variant: "destructive",diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ActionBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ActionBlockForm.test.tsxindex 27323a13a..9ae820455 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ActionBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ActionBlockForm.test.tsx@@ -44,6 +44,8 @@ vi.mock("../../workflowEditorUtils", () => ({getAvailableOutputParameterKeys: () => [],isNodeInsideForLoop: () => false,getParentLoopSkipsOnFail: () => false,+ isFirstBrowserTaskBlock: () => false,+ isMissingRequiredStartUrl: () => false,}));// Stub heavy child components so the test stays focused on the formdiff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsxindex 8d46acf5c..9ae5fba39 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsx@@ -162,6 +162,8 @@ vi.mock("../../workflowEditorUtils", () => ({getAvailableOutputParameterKeys: () => [],isNodeInsideForLoop: () => false,getParentLoopSkipsOnFail: () => false,+ isFirstBrowserTaskBlock: () => false,+ isMissingRequiredStartUrl: () => false,}));// Drive the dispatcher's `useReactFlow().getNode(blockId)` lookup via adiff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/NavigationBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/NavigationBlockForm.test.tsxindex 0c9666943..338800d84 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/NavigationBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/NavigationBlockForm.test.tsx@@ -58,6 +58,8 @@ vi.mock("../../workflowEditorUtils", () => ({getAvailableOutputParameterKeys: () => [],isNodeInsideForLoop: () => false,getParentLoopSkipsOnFail: () => false,+ isFirstBrowserTaskBlock: () => false,+ isMissingRequiredStartUrl: () => false,}));import { BLOCK_FORMS, BlockConfigForm } from "../BlockConfigForm";diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/URLBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/URLBlockForm.test.tsxindex 9374ce07e..46cbaf324 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/URLBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/URLBlockForm.test.tsx@@ -26,6 +26,8 @@ vi.mock("@xyflow/react", async () => {await vi.importActual<typeof import("@xyflow/react")>("@xyflow/react");return {...actual,+ useNodes: () => [...mockNodes.values()],+ useEdges: () => [],useReactFlow: () => ({getNode: (id: string) => mockNodes.get(id),updateNodeData,diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.tsindex 9f8b71257..0718d2890 100644--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts@@ -4442,12 +4442,26 @@ function leavesBrowserState(node: AppNode, nodes: Array<AppNode>): boolean {case "navigation":return node.data.engine !== RunEngine.SkyvernV2;case "loop":- case "conditional":// A container itself navigates nothing; its children do.return nodes.some((child) =>child.parentId === node.id && leavesBrowserState(child, nodes),);+ case "conditional":+ // Only the matched branch runs, so a page is open afterwards only when+ // every branch opens one and a default branch catches the no-match case.+ return (+ node.data.branches.some((branch) => branch.is_default) &&+ node.data.branches.every((branch) =>+ nodes.some(+ (child) =>+ child.parentId === node.id &&+ isWorkflowBlockNode(child) &&+ child.data.conditionalBranchId === branch.id &&+ leavesBrowserState(child, nodes),+ ),+ )+ );default:return false;}@@ -4465,6 +4479,33 @@ function isFirstBrowserTaskBlock(});}+// A run starts on about:blank, so the backend fails a first page-opening block that has no+// URL (MissingStarterUrl).+function isMissingRequiredStartUrl(+ nodes: Array<AppNode>,+ edges: Array<Edge>,+ id: string,+): boolean {+ const node = nodes.find((node) => node.id === id);+ if (!node) return false;+ switch (node.type) {+ case "task":+ case "navigation":+ case "action":+ case "extraction":+ case "login":+ case "url":+ case "fileDownload":+ return (+ node.data.url.trim() === "" &&+ leavesBrowserState(node, nodes) &&+ isFirstBrowserTaskBlock(nodes, edges, id)+ );+ default:+ return false;+ }+}+function convertParametersToParameterYAML(parameters: Array<Exclude<Parameter, OutputParameter>>,): Array<ParameterYAML> {@@ -5660,6 +5701,7 @@ export {getNestingLevel,getAvailableOutputParameterKeys,isFirstBrowserTaskBlock,+ isMissingRequiredStartUrl,urlMayBeGoogleDrive,getBlockNameOfOutputParameterKey,getDefaultValueForParameterType,diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunSummaryStrip.test.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunSummaryStrip.test.tsxindex 2045f3136..239e96ae0 100644--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunSummaryStrip.test.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunSummaryStrip.test.tsx@@ -119,3 +119,42 @@ describe("RunSummaryStrip status badge", () => {expect(screen.queryByRole("link")).toBeNull();});});++describe("RunSummaryStrip failure category", () => {+ test("a budget exhaustion reads as a run limit, not a billing error", async () => {+ renderStrip(+ makeRun({+ status: Status.Failed,+ failure_category: [+ {+ category: "BUDGET_EXHAUSTED",+ confidence_float: 1,+ reasoning: "max_turns",+ },+ ],+ }),+ );+ expect(screen.queryByText(/budget/i)).toBeNull();+ fireEvent.focus(screen.getByText("Step or time limit reached"));+ const tooltip = await screen.findByRole("tooltip");+ expect(within(tooltip).getByText(/billing or credits issue/)).toBeTruthy();+ });++ test("a workflow author's own error code is shown verbatim with its description", async () => {+ renderStrip(+ makeRun({+ status: Status.Failed,+ failure_category: [+ {+ category: "InvalidZip",+ confidence_float: 1,+ reasoning: "The ZIP code is not in the service area.",+ },+ ],+ }),+ );+ fireEvent.focus(screen.getByText("InvalidZip"));+ const tooltip = await screen.findByRole("tooltip");+ expect(within(tooltip).getByText(/not in the service area/)).toBeTruthy();+ });+});diff --git a/skyvern-frontend/src/routes/workflows/types/browserSessionTypes.ts b/skyvern-frontend/src/routes/workflows/types/browserSessionTypes.tsindex 3fe32d501..6b5f9a809 100644--- a/skyvern-frontend/src/routes/workflows/types/browserSessionTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/browserSessionTypes.ts@@ -17,6 +17,7 @@ interface BrowserSession {generate_browser_profile?: boolean;vnc_streaming_supported: boolean;stream_transport?: string | null;+ created_by?: string | null;}interface Recording {diff --git a/skyvern-frontend/src/routes/workflows/workflowBlockUtils.test.ts b/skyvern-frontend/src/routes/workflows/workflowBlockUtils.test.tsindex 82bdadf6b..ce4254737 100644--- a/skyvern-frontend/src/routes/workflows/workflowBlockUtils.test.ts+++ b/skyvern-frontend/src/routes/workflows/workflowBlockUtils.test.ts@@ -426,6 +426,7 @@ describe("getActionSummary", () => {reasoning: null,intention: "Tried to navigate to https://example.com/contact-us/",response: "https://example.com/contact-us/ (HTTP 404, dead end)",+ description: "task_v3 goto https://example.com/contact-us/",text: null,}),).toEqual({@@ -444,6 +445,7 @@ describe("getActionSummary", () => {reasoning: "**Following the footer link** to the contact page",intention: "Tried to navigate to https://example.com/contact-us/",response: "https://example.com/contact-us/ (HTTP 404, dead end)",+ description: "task_v3 goto https://example.com/contact-us/",}),).toEqual({body: {@@ -463,6 +465,7 @@ describe("getActionSummary", () => {reasoning: " ",intention: null,response: "https://example.com/contact-us/ (HTTP 404, dead end)",+ description: "task_v3 goto https://example.com/contact-us/",}),).toEqual({body: null,@@ -470,6 +473,25 @@ describe("getActionSummary", () => {});});+ // The agent stores its answer to its own user_detail_query in `response`, which is not a result.+ it("does not report an agent's user_detail_answer as an outcome", () => {+ expect(+ getActionSummary({+ action_type: ActionTypes.Click,+ reasoning: "Click the verify code button to submit the code.",+ intention: "Should I click the Verify code button?",+ response: "Yes, click the Verify code button.",+ description: null,+ }),+ ).toEqual({+ body: {+ text: "Click the verify code button to submit the code.",+ isProse: true,+ },+ outcome: null,+ });+ });+// A cached run writes the answer it typed to both text and response, and the card already prints// it on its Input line.it("does not report a typed value back as an outcome", () => {@@ -480,6 +502,7 @@ describe("getActionSummary", () => {intention: "Enter your zip code",response: "90210",text: "90210",+ created_by: "script",}),).toEqual({body: { text: "Enter your zip code", isProse: true },@@ -487,6 +510,22 @@ describe("getActionSummary", () => {});});+ it("reports the option a cached script selected, which it records nowhere else", () => {+ expect(+ getActionSummary({+ action_type: ActionTypes.SelectOption,+ reasoning: null,+ intention: "Choose the state",+ response: "California",+ text: null,+ created_by: "script",+ }),+ ).toEqual({+ body: { text: "Choose the state", isProse: true },+ outcome: "California",+ });+ });+// Paragraph breaks survive for a card that renders blocks; collapsing them here would flatten a// multi-paragraph provider summary into one run-on line.it("keeps the prose body as written", () => {diff --git a/skyvern-frontend/src/routes/workflows/workflowBlockUtils.ts b/skyvern-frontend/src/routes/workflows/workflowBlockUtils.tsindex 835e82da5..cbb00cb3a 100644--- a/skyvern-frontend/src/routes/workflows/workflowBlockUtils.ts+++ b/skyvern-frontend/src/routes/workflows/workflowBlockUtils.ts@@ -6,6 +6,7 @@ import {type ActionSummary,type ActionSummaryBody,} from "@/api/types";+import { isRecord } from "@/util/utils";import {isNestedLoopWorkflowBlock,@@ -185,10 +186,29 @@ export function taskV3CallText(export type ActionSummarySource = Partial<Pick<ActionsApiResponse,- "action_type" | "reasoning" | "intention" | "response" | "status" | "text"+ | "action_type"+ | "created_by"+ | "description"+ | "intention"+ | "output"+ | "reasoning"+ | "response"+ | "status"+ | "text">>;+// Only Task V3, code-block recorder and cached-script rows write a result into `response` (a script+// select records the option it chose there and nowhere else). The agent stores its+// `user_detail_answer` there and computer use its click coordinates, neither of which is a result.+function recordsOutcome(action: ActionSummarySource): boolean {+ return (+ action.created_by === "script" ||+ taskV3CallText(action.description) !== null ||+ (isRecord(action.output) && "code_line" in action.output)+ );+}+export function getActionInputValue(action: ActionSummarySource,): string | null {@@ -258,7 +278,9 @@ export function getActionSummary(break;}}- const recorded = normalizeInlineText(getActionOutcome(action));+ const recorded = recordsOutcome(action)+ ? normalizeInlineText(getActionOutcome(action))+ : null;const outcome =recorded !== null && recorded !== normalizeInlineText(body?.text)? recordeddiff --git a/skyvern-frontend/src/routes/workflows/workflowRun/ActionCard.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/ActionCard.tsxindex f71479d86..7a19271ba 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/ActionCard.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/ActionCard.tsx@@ -93,7 +93,7 @@ function ActionCard({ action, onClick, active, index, cardClassName }: Props) {{summary?.outcome && (<div className="break-words text-xs text-neutral-600 dark:text-slate-400"><span className="text-neutral-500 dark:text-slate-500">- Outcome:{" "}+ Result:{" "}</span>{summary.outcome}</div>diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsxindex e55ca16d4..df7364439 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx@@ -1603,6 +1603,7 @@ describe("WorkflowRunTimelineBlockItem", () => {text: null,intention: "Tried to navigate to https://example.com/contact-us/",response: "https://example.com/contact-us/ (HTTP 404, dead end)",+ description: "task_v3 goto https://example.com/contact-us/",created_by: null,confidence_float: null,},@@ -1656,7 +1657,9 @@ describe("WorkflowRunTimelineBlockItem", () => {/>,);- const summary = screen.getByText(`${TIMELINE_DESCRIPTOR_SEPARATOR} Click`);+ const summary = screen.getByText("Click", {+ selector: "[aria-hidden='true']",+ });expect(summary.className).not.toContain("sr-only");expect(screen.getByRole("button", { name: /Click/ }).getAttribute("title"),diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsxindex f49940001..2912e9b71 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx@@ -670,7 +670,6 @@ function TimelineActionRows({)}{summary?.body ? (<span className="min-w-0 truncate text-muted-foreground dark:text-slate-500">- ·{" "}{summary.body.isProse ? (<InlineMarkdown// One line: InlineMarkdown drops every paragraph break, so prose that@@ -688,15 +687,16 @@ function TimelineActionRows({// A Task V3 turn that emitted only tool calls leaves every action of that round// with no prose, which used to render as a bare icon and index. Show the type// label sighted readers were missing; it duplicates the sr-only label above, so- // assistive tech must not read it twice. Error rows already show theirs, and a- // row that recorded an outcome says something better below.- !summary?.outcome &&+ // assistive tech must not read it twice. Error rows already show theirs.tone !== "error" && (<spanaria-hidden="true"- className="min-w-0 flex-1 truncate text-muted-foreground dark:text-slate-500"+ className={cn(+ "truncate text-muted-foreground dark:text-slate-500",+ summary?.outcome ? "shrink-0" : "min-w-0 flex-1",+ )}>- · {label}+ {label}</span>))}@@ -710,7 +710,9 @@ function TimelineActionRows({summary.body ? "max-w-[60%] shrink-0" : "min-w-0 flex-1",)}>- · Outcome: {summary.outcome}+ <span aria-hidden="true">→ </span>+ <span className="sr-only">Result: </span>+ {summary.outcome}</span>)}</button>diff --git a/skyvern-frontend/src/store/MissingStartUrlStore.ts b/skyvern-frontend/src/store/MissingStartUrlStore.tsnew file mode 100644index 000000000..d3719ab5f--- /dev/null+++ b/skyvern-frontend/src/store/MissingStartUrlStore.ts@@ -0,0 +1,24 @@+import { create } from "zustand";++type MissingStartUrlState = {+ // Blocks whose run was refused for a missing starting URL; their editors+ // highlight the URL field until one is entered.+ flaggedBlockIds: ReadonlySet<string>;+ flag: (blockId: string) => void;+ clear: (blockId: string) => void;+};++export const useMissingStartUrlStore = create<MissingStartUrlState>((set) => ({+ flaggedBlockIds: new Set(),+ flag: (blockId) =>+ set((state) => ({+ flaggedBlockIds: new Set(state.flaggedBlockIds).add(blockId),+ })),+ clear: (blockId) =>+ set((state) => {+ if (!state.flaggedBlockIds.has(blockId)) return state;+ const next = new Set(state.flaggedBlockIds);+ next.delete(blockId);+ return { flaggedBlockIds: next };+ }),+}));diff --git a/skyvern-frontend/src/util/failureCategoryDisplay.ts b/skyvern-frontend/src/util/failureCategoryDisplay.tsnew file mode 100644index 000000000..8a3b20968--- /dev/null+++ b/skyvern-frontend/src/util/failureCategoryDisplay.ts@@ -0,0 +1,130 @@+import type { FailureCategory } from "@/api/types";++// Mirrors FailureCategory in skyvern/forge/failure_classifier.py. Workflow authors can also raise+// their own free-form error codes as the category; those are shown verbatim because customers match+// on the exact code, with the author's description (carried in `reasoning`) as the explanation.+type FailureCategoryDisplay = {+ label: string;+ description: string;+};++const FAILURE_CATEGORY_DISPLAY = {+ ANTI_BOT_DETECTION: {+ label: "Blocked by bot protection",+ description:+ "The site showed a CAPTCHA or bot check that the run couldn't get past.",+ },+ PROXY_ERROR: {+ label: "Proxy connection failed",+ description:+ "The run couldn't connect through its proxy. Retry, or try a different proxy location.",+ },+ BROWSER_ERROR: {+ label: "Browser error",+ description:+ "The browser crashed or the page closed unexpectedly. Retrying usually helps.",+ },+ NAVIGATION_FAILURE: {+ label: "Couldn't open the page",+ description:+ "The page didn't load or redirected somewhere unexpected, such as a 404. Check the URL.",+ },+ PAGE_LOAD_TIMEOUT: {+ label: "Page load timed out",+ description:+ "The page didn't finish loading in time. Check the URL, or retry if the site is slow.",+ },+ ELEMENT_STATE_TIMEOUT: {+ label: "Element never became ready",+ description:+ "An element on the page didn't become visible or clickable in time.",+ },+ AUTH_FAILURE: {+ label: "Login failed",+ description:+ "The run couldn't sign in to the site, for example because the login or a 2FA step was rejected.",+ },+ LLM_ERROR: {+ label: "AI model error",+ description:+ "The AI model running this task returned an error or didn't respond. This is usually temporary, so retry the run.",+ },+ CREDENTIAL_ERROR: {+ label: "Credential problem",+ description:+ "The credentials for this run are missing or couldn't be used. Check the credentials it uses.",+ },+ DATA_EXTRACTION_FAILURE: {+ label: "Couldn't extract data",+ description:+ "The run couldn't read or extract the requested data from the page. Check that the page loaded correctly and, if extracting, the goal and schema.",+ },+ ELEMENT_NOT_FOUND: {+ label: "Element not found",+ description: "The run couldn't find the element it needed on the page.",+ },+ WRONG_PAGE_STATE: {+ label: "Unexpected page",+ description:+ "The site showed a different page or state than the run expected.",+ },+ MAX_STEPS_EXCEEDED: {+ label: "Step limit reached",+ description:+ "The run used its maximum number of steps before finishing. Raise the step limit or simplify the goal.",+ },+ // Task V3 run caps: steps, turns, tool calls, tokens, or wall-clock time.+ BUDGET_EXHAUSTED: {+ label: "Step or time limit reached",+ description:+ "The run hit its step or time limit before finishing. This isn't a billing or credits issue. Raise the step limit or simplify the goal.",+ },+ LLM_REASONING_ERROR: {+ label: "AI chose the wrong action",+ description:+ "The AI misread the page or took the wrong action. A more specific goal often helps.",+ },+ INFRASTRUCTURE_ERROR: {+ label: "Temporary system issue",+ description:+ "Something went wrong on Skyvern's side, such as a network or capacity problem. Retrying usually helps.",+ },+ PARAMETER_BINDING_ERROR: {+ label: "Parameter setup failed",+ description:+ "An internal setup step for this run's parameters failed. Retry, or contact support if it persists.",+ },+ UNKNOWN: {+ label: "Unknown failure",+ description:+ "Skyvern couldn't determine the cause. See the failure reason for details.",+ },+} satisfies Record<string, FailureCategoryDisplay>;++type KnownFailureCategory = keyof typeof FAILURE_CATEGORY_DISPLAY;++function isKnownFailureCategory(+ category: string,+): category is KnownFailureCategory {+ return Object.prototype.hasOwnProperty.call(+ FAILURE_CATEGORY_DISPLAY,+ category,+ );+}++function getFailureCategoryDisplay({+ category,+ reasoning,+}: Pick<FailureCategory, "category" | "reasoning">): FailureCategoryDisplay {+ if (isKnownFailureCategory(category)) {+ return FAILURE_CATEGORY_DISPLAY[category];+ }+ return {+ label: category,+ description:+ (typeof reasoning === "string" && reasoning.trim()) ||+ "See the failure reason for details.",+ };+}++export { getFailureCategoryDisplay };diff --git a/skyvern/config.py b/skyvern/config.pyindex 59acc3842..a8954fc98 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -541,6 +541,10 @@ class Settings(BaseSettings):# (SKY-16501). Force-on term only: runs are randomized per run by the flag of the same name, read# through run_arm_enabled(TYPE_COORDINATE_CLICK_FLAG, ...). Off: the field is reached by focus() alone.TASK_V3_TYPE_COORDINATE_CLICK: bool = False+ # Press a sub-pixel date segment through the layer painted over it, and route month/year and+ # year-only segment groups to the segment path (SKY-17013). Force-on term only: runs are randomized per+ # run by the flag of the same name, read through run_arm_enabled(DATE_SEGMENT_AIM_FLAG, ...).+ TASK_V3_DATE_SEGMENT_AIM: bool = False# Render the previous block's outcome (status / finish reason / final URL) and whether this is the# last block into a v3 block's goal. Costs prompt tokens on every turn of the block, so it is# measured via taskv3_block_context_tokens before it earns default-on. The outcome itself isdiff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 1b2f12397..290c1dc88 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -193,6 +193,7 @@ from skyvern.forge.taskv3.loop import LoopOutcome, RoundActionfrom skyvern.forge.taskv3.pre_submit_capture import PreSubmitCaptureRing, is_run_sampled, pre_submit_screenshotfrom skyvern.forge.taskv3.run_arms import (CUSTOMER_PRECEDENCE_FLAG,+ DATE_SEGMENT_AIM_FLAG,EXTRACTION_REPORTS_FLAG,GOAL_CHECK_ENFORCE_FLAG,GOAL_CHECK_FLAG,@@ -2258,6 +2259,13 @@ class ForgeAgent:organization_id=task.organization_id,forced=settings.TASK_V3_TYPE_COORDINATE_CLICK,)+ await resolve_run_arm(+ context,+ DATE_SEGMENT_AIM_FLAG,+ distinct_id=task.workflow_run_id or task.task_id,+ organization_id=task.organization_id,+ forced=settings.TASK_V3_DATE_SEGMENT_AIM,+ )await resolve_run_arm(context,UNANSWERABLE_FIELD_REMEDY_FLAG,diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex 404eb1336..bf76504c4 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -1972,6 +1972,7 @@ async def _provision_browser_session(ctx: AgentContext) -> BuildTestConnectFailusession = await app.PERSISTENT_SESSIONS_MANAGER.create_session(organization_id=ctx.organization_id,timeout_minutes=30,+ created_by="copilot",)if ctx.browser_session_id:# A sibling call installed a session while this create was in flight. Adopt theirs anddiff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.pyindex fe328a5ce..55ed73e3e 100644--- a/skyvern/forge/sdk/db/models.py+++ b/skyvern/forge/sdk/db/models.py@@ -267,6 +267,13 @@ class OrganizationSMSConfigModel(Base):postgresql_where=text("mode = 'connected' AND deleted_at IS NULL"),sqlite_where=text("mode = 'connected' AND deleted_at IS NULL"),),+ Index(+ "uq_org_sms_configs_one_managed",+ "organization_id",+ unique=True,+ postgresql_where=text("mode = 'managed' AND deleted_at IS NULL"),+ sqlite_where=text("mode = 'managed' AND deleted_at IS NULL"),+ ),UniqueConstraint("sms_config_id","organization_id",@@ -279,6 +286,8 @@ class OrganizationSMSConfigModel(Base):mode = Column(String, nullable=False)encrypted_webhook_secret = Column(String, nullable=False)webhook_secret_encrypted_method = Column(String, nullable=False, default="aes", server_default="aes")+ encrypted_signing_token = Column(String, nullable=True)+ signing_token_encrypted_method = Column(String, nullable=True)daily_ingest_cap = Column(Integer, nullable=False, default=100, server_default="100")created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)modified_at = Column(@@ -311,8 +320,8 @@ class OrganizationPhoneNumberModel(Base):"organization_id","phone_number",unique=True,- postgresql_where=text("status = 'active' AND deleted_at IS NULL"),- sqlite_where=text("status = 'active' AND deleted_at IS NULL"),+ postgresql_where=text("status IN ('active', 'provisioning', 'quarantined') AND deleted_at IS NULL"),+ sqlite_where=text("status IN ('active', 'provisioning', 'quarantined') AND deleted_at IS NULL"),),)@@ -330,6 +339,7 @@ class OrganizationPhoneNumberModel(Base):price_cents = Column(Integer, nullable=True)status = Column(String, nullable=False, default="active", server_default="active")quarantined_until = Column(DateTime, nullable=True)+ provisioning_claimed_at = Column(DateTime, nullable=True)created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)modified_at = Column(DateTime,@@ -1635,6 +1645,7 @@ class PersistentBrowserSessionModel(Base):# Retained, unwritten column: the asynchronous-create contract that populated it was reverted,# and dropping it would rewrite a hot table for no gain. Keep it in sync with `alembic check`.provisioning_deadline_at = Column(DateTime, nullable=True)+ created_by = Column(String, nullable=True)created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False, index=True)modified_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow, nullable=False)deleted_at = Column(DateTime, nullable=True)@@ -1828,6 +1839,7 @@ class CredentialModel(Base):proxy_location = Column(String, nullable=True)proxy_session_id = Column(String, nullable=True)folder_id = Column(String, ForeignKey("credential_folders.folder_id", ondelete="SET NULL"), nullable=True)+ created_by = Column(String, nullable=True)created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)modified_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow, nullable=False)diff --git a/skyvern/forge/sdk/db/repositories/browser_sessions.py b/skyvern/forge/sdk/db/repositories/browser_sessions.pyindex 14bd775c1..8fab72ecb 100644--- a/skyvern/forge/sdk/db/repositories/browser_sessions.py+++ b/skyvern/forge/sdk/db/repositories/browser_sessions.py@@ -988,6 +988,7 @@ class BrowserSessionsRepository(BaseRepository):bound_key: str | None = None,download_run_id: str | None = None,*,+ created_by: str | None = None,workflow_run_id: str | None = None,attempt_number: int | None = None,dispatch_claim_started_at: datetime | None = None,@@ -1047,6 +1048,7 @@ class BrowserSessionsRepository(BaseRepository):provisioning_deadline_at=to_naive_utc(provisioning_deadline_at),bound_workflow_permanent_id=bound_workflow_permanent_id,bound_key=bound_key,+ created_by=created_by,)session.add(browser_session)await session.flush()diff --git a/skyvern/forge/sdk/db/repositories/credentials.py b/skyvern/forge/sdk/db/repositories/credentials.pyindex 73bd86360..b68820a0e 100644--- a/skyvern/forge/sdk/db/repositories/credentials.py+++ b/skyvern/forge/sdk/db/repositories/credentials.py@@ -44,6 +44,7 @@ class CredentialRepository(BaseRepository):tested_url: str | None = None,proxy_location: ProxyLocationInput = None,proxy_session_id: str | None = None,+ created_by: str | None = None,) -> Credential:proxy_location, proxy_session_id = normalize_proxy_pin_for_create(proxy_location=proxy_location,@@ -67,6 +68,7 @@ class CredentialRepository(BaseRepository):tested_url=tested_url,proxy_location=serialized_proxy_location,proxy_session_id=proxy_session_id,+ created_by=created_by,)session.add(credential)await session.flush()diff --git a/skyvern/forge/sdk/db/repositories/sms.py b/skyvern/forge/sdk/db/repositories/sms.pyindex 21b677f90..932ceb237 100644--- a/skyvern/forge/sdk/db/repositories/sms.py+++ b/skyvern/forge/sdk/db/repositories/sms.py@@ -3,11 +3,11 @@ from __future__ import annotationsimport asynciofrom collections import defaultdictfrom collections.abc import AsyncIterator-from contextlib import asynccontextmanager-from datetime import datetime-from typing import cast+from contextlib import AsyncExitStack, asynccontextmanager+from datetime import datetime, timedelta+from typing import Any, ClassVar, cast-from sqlalchemy import case, func, select, text+from sqlalchemy import case, func, or_, select, text, updatefrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncEngine, AsyncSessionfrom sqlalchemy.pool import QueuePool@@ -91,6 +91,13 @@ async def _lock_sms_configs(return {row.sms_config_id: row for row in rows}+LIFECYCLE_LOCK_TIMEOUT_SECONDS = 10.0+++class SMSLifecycleLockTimeout(TimeoutError):+ """The SMS lifecycle lock acquisition deadline expired."""++_POSTGRES_LIFECYCLE_SERIALIZER = asyncio.Lock()_POSTGRES_LIFECYCLE_SEMAPHORES: dict[int, asyncio.Semaphore] = {}@@ -102,7 +109,7 @@ async def _encrypt_previous_sms_url(value: str | None, organization_id: str) ->class SMSRepository(BaseRepository):- _local_advisory_locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)+ _local_advisory_locks: ClassVar[defaultdict[str, asyncio.Lock]] = defaultdict(asyncio.Lock)def _postgres_pool_info(self) -> tuple[bool, int | None, int | None]:bind: AsyncEngine | None = self.Session.kw.get("bind")@@ -121,7 +128,12 @@ class SMSRepository(BaseRepository):if not is_postgres:yieldreturn- if pool_key is None or pool_capacity is None or pool_capacity <= 1:+ if pool_capacity is not None and pool_capacity < 2:+ raise ValueError(+ "PostgreSQL lifecycle locks require at least 2 total pooled connections "+ f"(pool size + max overflow); configured capacity is {pool_capacity}."+ )+ if pool_key is None or pool_capacity is None:async with _POSTGRES_LIFECYCLE_SERIALIZER:yieldreturn@@ -139,33 +151,52 @@ class SMSRepository(BaseRepository):if phone_number is not None:normalized_phone_number = normalize_phone_identifier(phone_number)lock_keys.append(f"twilio-sms:phone:{organization_id}:{normalized_phone_number}")- async with self._lifecycle_permit():- async with self.Session() as session:- bind = session.get_bind()- is_postgres = bind.dialect.name == "postgresql"- if not is_postgres:- acquired_locks: list[asyncio.Lock] = []- try:+ deadline = asyncio.get_running_loop().time() + LIFECYCLE_LOCK_TIMEOUT_SECONDS+ async with AsyncExitStack() as stack:+ session: AsyncSession | None = None+ is_postgres = False+ acquired_keys: list[str] = []+ try:+ async with asyncio.timeout_at(deadline):+ await stack.enter_async_context(self._lifecycle_permit())+ session = cast(AsyncSession, await stack.enter_async_context(self.Session()))+ is_postgres = session.get_bind().dialect.name == "postgresql"+ if is_postgres:+ # Checkout is included in the same deadline as all lock waits.+ await session.connection()+ for lock_key in lock_keys:+ while not await session.scalar(+ text("SELECT pg_try_advisory_lock(hashtextextended(:lock_key, 0))"),+ {"lock_key": lock_key},+ ):+ await asyncio.sleep(0.05)+ acquired_keys.append(lock_key)+ else:for lock_key in lock_keys:lock = self._local_advisory_locks[lock_key]await lock.acquire()- acquired_locks.append(lock)- yield- finally:- for lock in reversed(acquired_locks):- lock.release()- return- lock_sql = text("SELECT pg_advisory_lock(hashtextextended(:lock_key, 0))")- unlock_sql = text("SELECT pg_advisory_unlock(hashtextextended(:lock_key, 0))")- acquired_keys: list[str] = []- try:- for lock_key in lock_keys:- await session.execute(lock_sql, {"lock_key": lock_key})- acquired_keys.append(lock_key)- yield- finally:- for lock_key in reversed(acquired_keys):- await session.execute(unlock_sql, {"lock_key": lock_key})+ stack.callback(lock.release)+ except BaseException as exc:+ if is_postgres and session is not None:+ # Cancellation can race the server granting a lock. Discard the+ # connection, including any lock whose result was never received.+ await session.invalidate()+ if isinstance(exc, TimeoutError):+ raise SMSLifecycleLockTimeout("SMS lifecycle lock acquisition timed out") from exc+ raise+ try:+ yield+ finally:+ if is_postgres and session is not None:+ try:+ for lock_key in reversed(acquired_keys):+ await session.execute(+ text("SELECT pg_advisory_unlock(hashtextextended(:lock_key, 0))"),+ {"lock_key": lock_key},+ )+ except BaseException:+ await session.invalidate()+ raise@asynccontextmanagerasync def organization_lock(self, organization_id: str) -> AsyncIterator[None]:@@ -201,14 +232,17 @@ class SMSRepository(BaseRepository):except IntegrityError as error:_hide_integrity_error_parameters(error)await session.rollback()- if mode != "connected":+ if mode not in {"connected", "managed"}:raisewinner = await session.scalar(- select(OrganizationSMSConfigModel).where(+ select(OrganizationSMSConfigModel)+ .where(OrganizationSMSConfigModel.organization_id == organization_id,- OrganizationSMSConfigModel.mode == "connected",+ OrganizationSMSConfigModel.mode == mode,OrganizationSMSConfigModel.deleted_at.is_(None),)+ .order_by(OrganizationSMSConfigModel.created_at)+ .limit(1))if winner is None:raise@@ -263,6 +297,43 @@ class SMSRepository(BaseRepository):)return SMSConfig.model_validate(row), webhook_secret+ @db_operation("set_sms_config_signing_token")+ async def set_sms_config_signing_token(+ self,+ sms_config_id: str,+ organization_id: str,+ auth_token: str,+ ) -> None:+ async with self.Session() as session:+ row = await session.scalar(+ select(OrganizationSMSConfigModel).where(+ OrganizationSMSConfigModel.sms_config_id == sms_config_id,+ OrganizationSMSConfigModel.organization_id == organization_id,+ OrganizationSMSConfigModel.deleted_at.is_(None),+ )+ )+ if row is None:+ return+ row.encrypted_signing_token = await encryptor.encrypt(auth_token, EncryptMethod.AES)+ row.signing_token_encrypted_method = EncryptMethod.AES.value+ await session.commit()++ @db_operation("get_sms_config_signing_token")+ async def get_sms_config_signing_token(self, sms_config_id: str) -> str | None:+ async with self.Session() as session:+ row = await session.scalar(+ select(OrganizationSMSConfigModel).where(+ OrganizationSMSConfigModel.sms_config_id == sms_config_id,+ OrganizationSMSConfigModel.deleted_at.is_(None),+ )+ )+ if row is None or row.encrypted_signing_token is None or row.signing_token_encrypted_method is None:+ return None+ return await encryptor.decrypt(+ row.encrypted_signing_token,+ EncryptMethod(row.signing_token_encrypted_method),+ )+@db_operation("get_sms_config")async def get_sms_config(self,@@ -301,6 +372,27 @@ class SMSRepository(BaseRepository):)return SMSConfig.model_validate(row), webhook_secret+ @db_operation("get_managed_sms_config")+ async def get_managed_sms_config(self, organization_id: str) -> tuple[SMSConfig, str] | None:+ async with self.Session() as session:+ row = await session.scalar(+ select(OrganizationSMSConfigModel)+ .where(+ OrganizationSMSConfigModel.organization_id == organization_id,+ OrganizationSMSConfigModel.mode == "managed",+ OrganizationSMSConfigModel.deleted_at.is_(None),+ )+ .order_by(OrganizationSMSConfigModel.created_at)+ .limit(1)+ )+ if row is None:+ return None+ webhook_secret = await encryptor.decrypt(+ row.encrypted_webhook_secret,+ EncryptMethod(row.webhook_secret_encrypted_method),+ )+ return SMSConfig.model_validate(row), webhook_secret+@db_operation("list_sms_configs")async def list_sms_configs(self, organization_id: str) -> list[SMSConfig]:async with self.Session() as session:@@ -468,6 +560,27 @@ class SMSRepository(BaseRepository):)return OrganizationPhoneNumber.model_validate(row) if row is not None else None+ @db_operation("get_active_phone_number_by_number")+ async def get_active_phone_number_by_number(+ self,+ phone_number: str,+ *,+ organization_id: str,+ ) -> OrganizationPhoneNumber | None:+ if not looks_like_phone_identifier(phone_number):+ return None+ normalized = normalize_phone_identifier(phone_number)+ async with self.Session() as session:+ row = await session.scalar(+ select(OrganizationPhoneNumberModel).where(+ OrganizationPhoneNumberModel.phone_number == normalized,+ OrganizationPhoneNumberModel.organization_id == organization_id,+ OrganizationPhoneNumberModel.status == "active",+ OrganizationPhoneNumberModel.deleted_at.is_(None),+ )+ )+ return OrganizationPhoneNumber.model_validate(row) if row is not None else None+@db_operation("get_phone_number")async def get_phone_number(self, phone_number_id: str, organization_id: str) -> OrganizationPhoneNumber | None:async with self.Session() as session:@@ -512,6 +625,9 @@ class SMSRepository(BaseRepository):previous_sms_application_sid: str | None | object = _UNSET,credential_id: str | None | object = _UNSET,quarantined_until: datetime | None | object = _UNSET,+ price_cents: int | None | object = _UNSET,+ provider_cost_cents: int | None | object = _UNSET,+ provisioning_claimed_at: datetime | None | object = _UNSET,) -> OrganizationPhoneNumber | None:if status is not None and status not in PHONE_NUMBER_STATUSES:raise InvalidPhoneNumberStatus("Invalid phone number status")@@ -561,6 +677,12 @@ class SMSRepository(BaseRepository):row.credential_id = cast(str | None, credential_id)if quarantined_until is not _UNSET:row.quarantined_until = to_naive_utc(cast(datetime | None, quarantined_until))+ if price_cents is not _UNSET:+ row.price_cents = cast(int | None, price_cents)+ if provider_cost_cents is not _UNSET:+ row.provider_cost_cents = cast(int | None, provider_cost_cents)+ if provisioning_claimed_at is not _UNSET:+ row.provisioning_claimed_at = to_naive_utc(cast(datetime | None, provisioning_claimed_at))row.modified_at = naive_utc_now()try:await session.commit()@@ -574,3 +696,84 @@ class SMSRepository(BaseRepository):raiseawait session.refresh(row)return OrganizationPhoneNumber.model_validate(row)++ @db_operation("update_phone_number_if_claimed")+ async def update_phone_number_if_claimed(+ self,+ phone_number_id: str,+ organization_id: str,+ claim_token: datetime,+ status: str | None = None,+ provider_number_sid: str | None | object = _UNSET,+ price_cents: int | None | object = _UNSET,+ provider_cost_cents: int | None | object = _UNSET,+ quarantined_until: datetime | None | object = _UNSET,+ provisioning_claimed_at: datetime | None | object = _UNSET,+ ) -> OrganizationPhoneNumber | None:+ """Apply a phone update only while the caller owns its claim token."""+ if status is not None and status not in PHONE_NUMBER_STATUSES:+ raise InvalidPhoneNumberStatus("Invalid phone number status")+ values: dict[str, Any] = {"modified_at": naive_utc_now()}+ if status is not None:+ values["status"] = status+ for key, value in (+ ("provider_number_sid", provider_number_sid),+ ("price_cents", price_cents),+ ("provider_cost_cents", provider_cost_cents),+ ("quarantined_until", quarantined_until),+ ("provisioning_claimed_at", provisioning_claimed_at),+ ):+ if value is not _UNSET:+ values[key] = to_naive_utc(value) if isinstance(value, datetime) else value+ async with self.Session() as session:+ row = await session.scalar(+ update(OrganizationPhoneNumberModel)+ .where(+ OrganizationPhoneNumberModel.phone_number_id == phone_number_id,+ OrganizationPhoneNumberModel.organization_id == organization_id,+ OrganizationPhoneNumberModel.provisioning_claimed_at == to_naive_utc(claim_token),+ OrganizationPhoneNumberModel.deleted_at.is_(None),+ )+ .values(**values)+ .returning(OrganizationPhoneNumberModel)+ )+ await session.commit()+ if row is None:+ return None+ await session.refresh(row)+ return OrganizationPhoneNumber.model_validate(row)++ @db_operation("claim_phone_number_provisioning")+ async def claim_phone_number_provisioning(+ self,+ phone_number_id: str,+ organization_id: str,+ *,+ stale_after: timedelta = timedelta(minutes=5),+ ) -> OrganizationPhoneNumber | None:+ claimed_at = naive_utc_now()+ stale_before = claimed_at - stale_after+ async with self.Session() as session:+ row = await session.scalar(+ update(OrganizationPhoneNumberModel)+ .where(+ OrganizationPhoneNumberModel.phone_number_id == phone_number_id,+ OrganizationPhoneNumberModel.organization_id == organization_id,+ OrganizationPhoneNumberModel.status == "provisioning",+ OrganizationPhoneNumberModel.deleted_at.is_(None),+ or_(+ OrganizationPhoneNumberModel.provisioning_claimed_at.is_(None),+ OrganizationPhoneNumberModel.provisioning_claimed_at < stale_before,+ ),+ )+ .values(+ provisioning_claimed_at=claimed_at,+ modified_at=claimed_at,+ )+ .returning(OrganizationPhoneNumberModel)+ )+ await session.commit()+ if row is None:+ return None+ await session.refresh(row)+ return OrganizationPhoneNumber.model_validate(row)diff --git a/skyvern/forge/sdk/routes/browser_sessions.py b/skyvern/forge/sdk/routes/browser_sessions.pyindex 2ee61de61..c33b622e0 100644--- a/skyvern/forge/sdk/routes/browser_sessions.py+++ b/skyvern/forge/sdk/routes/browser_sessions.py@@ -183,6 +183,7 @@ async def get_browser_sessions_all(async def create_browser_session(browser_session_request: CreateBrowserSessionRequest = CreateBrowserSessionRequest(),current_org: Organization = Depends(org_auth_service.get_current_org),+ user_id: str | None = Depends(org_auth_service.get_current_user_id_or_none),) -> BrowserSessionResponse:timeout_minutes = browser_session_request.timeouttimeout_warning: str | None = None@@ -234,6 +235,7 @@ async def create_browser_session(browser_profile_id=browser_session_request.browser_profile_id,generate_browser_profile=browser_session_request.generate_browser_profile,needs_live_view=browser_session_request.needs_live_view,+ created_by=user_id,)response = await BrowserSessionResponse.from_browser_session(browser_session)response.warning = timeout_warningdiff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex 4fb5216fe..af761dd08 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -726,7 +726,11 @@ async def create_credential()try:- credential = await credential_service.create_credential(organization_id=current_org.organization_id, data=data)+ credential = await credential_service.create_credential(+ organization_id=current_org.organization_id,+ data=data,+ created_by=current_user_id,+ )except SkyvernHttpException as e:detail = (f"Custom credential service returned {e.error_message}"@@ -968,6 +972,7 @@ async def test_login(description="The login credentials and URL to test",),current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),+ current_user_id: str | None = Depends(org_auth_service.get_current_user_id_or_none),x_user_agent: Annotated[str | None, Header()] = None,) -> TestLoginResponse:"""Test a login with inline credentials without requiring a saved credential."""@@ -994,6 +999,7 @@ async def test_login(credential = await credential_service.create_credential(organization_id=organization_id,data=create_request,+ created_by=current_user_id,)if credential.vault_type == CredentialVaultType.BITWARDEN:@@ -3486,6 +3492,7 @@ def _convert_to_response(credential: Credential) -> CredentialResponse:folder_id=credential.folder_id,proxy_location=credential.proxy_location,proxy_session_id=credential.proxy_session_id,+ created_by=credential.created_by,)elif credential.credential_type == CredentialType.CREDIT_CARD:credential_response = CreditCardCredentialResponse(@@ -3508,6 +3515,7 @@ def _convert_to_response(credential: Credential) -> CredentialResponse:folder_id=credential.folder_id,proxy_location=credential.proxy_location,proxy_session_id=credential.proxy_session_id,+ created_by=credential.created_by,)elif credential.credential_type == CredentialType.SECRET:credential_response = SecretCredentialResponse(secret_label=credential.secret_label)@@ -3527,6 +3535,7 @@ def _convert_to_response(credential: Credential) -> CredentialResponse:folder_id=credential.folder_id,proxy_location=credential.proxy_location,proxy_session_id=credential.proxy_session_id,+ created_by=credential.created_by,)else:raise HTTPException(status_code=400, detail="Credential type not supported")diff --git a/skyvern/forge/sdk/routes/debug_sessions.py b/skyvern/forge/sdk/routes/debug_sessions.pyindex e64ecf0f7..9ac666039 100644--- a/skyvern/forge/sdk/routes/debug_sessions.py+++ b/skyvern/forge/sdk/routes/debug_sessions.py@@ -265,6 +265,7 @@ async def prewarm_debug_session(runnable_type=PREWARM_PENDING_RUNNABLE_TYPE,wait_for_startup=False,needs_live_view=True,+ created_by=current_user_id,)except IntegrityError:return Response(status_code=status.HTTP_202_ACCEPTED)@@ -629,6 +630,7 @@ async def new_debug_session(proxy_location=proxy_location,wait_for_startup=settings.ENV != "local",needs_live_view=True,+ created_by=current_user_id,)debug_session = await app.DATABASE.debug.create_debug_session(diff --git a/skyvern/forge/sdk/routes/sms_inbound.py b/skyvern/forge/sdk/routes/sms_inbound.pyindex b9d72dfa1..8642cd4cd 100644--- a/skyvern/forge/sdk/routes/sms_inbound.py+++ b/skyvern/forge/sdk/routes/sms_inbound.py@@ -3,11 +3,13 @@ from typing import Annotatedimport structlogfrom fastapi import APIRouter, BackgroundTasks, Header, HTTPException, Query, Request, Response, status+from pydantic import ValidationErrorfrom skyvern.config import settingsfrom skyvern.forge import appfrom skyvern.forge.sdk.db.datetime_utils import naive_utc_nowfrom skyvern.forge.sdk.db.enums import OrganizationAuthTokenType+from skyvern.forge.sdk.schemas.organizations import TwilioCredentialfrom skyvern.forge.sdk.schemas.totp_codes import OTPTypefrom skyvern.forge.sdk.services.twilio_service import build_inbound_sms_url, validate_twilio_signaturefrom skyvern.services.otp_service import parse_otp_login, redact_otp_identifier_for_log@@ -55,7 +57,11 @@ async def receive_inbound_sms(token: Annotated[str | None, Query()] = None,twilio_signature: Annotated[str | None, Header(alias="X-Twilio-Signature")] = None,) -> Response:- config_with_secret = await app.DATABASE.sms.get_sms_config_with_secret_for_inbound(sms_config_id=sms_config_id)+ try:+ config_with_secret = await app.DATABASE.sms.get_sms_config_with_secret_for_inbound(sms_config_id=sms_config_id)+ except ValidationError:+ LOG.error("Rejecting invalid persisted SMS configuration", sms_config_id=sms_config_id)+ raise HTTPException(status_code=403, detail="Invalid SMS configuration") from Noneif config_with_secret is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="SMS configuration not found")@@ -63,26 +69,36 @@ async def receive_inbound_sms(if not hmac.compare_digest(token or "", webhook_secret):raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid webhook token")- if sms_config.mode == "managed":- LOG.warning(- "Rejecting managed inbound SMS until managed signing credentials are persisted",- organization_id=sms_config.organization_id,- sms_config_id=sms_config.sms_config_id,- )- raise HTTPException(- status_code=status.HTTP_403_FORBIDDEN,- detail="Managed SMS signing token is unavailable",- )-form = await request.form()form_params = {key: value if isinstance(value, str) else str(value) for key, value in form.items()}- if sms_config.mode == "connected":+ auth_token: str | None = None+ if sms_config.mode == "managed":+ try:+ auth_token = await app.DATABASE.sms.get_sms_config_signing_token(sms_config_id)+ except Exception as exc:+ LOG.warning(+ "Rejecting managed inbound SMS without a decryptable signing token",+ organization_id=sms_config.organization_id,+ sms_config_id=sms_config.sms_config_id,+ exception_type=type(exc).__name__,+ )+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="Managed SMS signing token is unavailable",+ ) from exc+ if not auth_token:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="Managed SMS signing token is unavailable",+ )+ elif sms_config.mode == "connected":twilio_token = await app.DATABASE.organizations.get_valid_org_auth_token(sms_config.organization_id,OrganizationAuthTokenType.twilio_credential.value,)- auth_token = twilio_token.credential.auth_token if twilio_token is not None else None+ if twilio_token is not None and isinstance(twilio_token.credential, TwilioCredential):+ auth_token = twilio_token.credential.auth_tokenif not auth_token:LOG.warning("Rejecting inbound SMS because the connected Twilio auth token is unavailable",@@ -94,6 +110,14 @@ async def receive_inbound_sms(detail="Connected SMS signing token is unavailable",)+ elif sms_config.mode == "manual":+ # Manual forwarding trusts only the per-config webhook token checked above.+ pass+ else:+ LOG.error("Rejecting unknown SMS mode", sms_config_id=sms_config_id)+ raise HTTPException(status_code=403, detail="Invalid SMS configuration mode")++ if auth_token:base_url = settings.SKYVERN_BASE_URL.strip()if not base_url:LOG.error(@@ -115,11 +139,10 @@ async def receive_inbound_sms(redacted_identifier = redact_otp_identifier_for_log(to_identifier)phone_number = await app.DATABASE.sms.get_phone_number_by_number(to_identifier,- sms_config.organization_id,+ organization_id=sms_config.organization_id,)if (phone_number is None- or phone_number.organization_id != sms_config.organization_idor phone_number.sms_config_id != sms_config.sms_config_idor phone_number.status not in {"active", "releasing"}):diff --git a/skyvern/forge/sdk/routes/twilio_integration.py b/skyvern/forge/sdk/routes/twilio_integration.pyindex ddca0ba25..4cbe2a80d 100644--- a/skyvern/forge/sdk/routes/twilio_integration.py+++ b/skyvern/forge/sdk/routes/twilio_integration.py@@ -11,6 +11,7 @@ from pydantic import BaseModel, ConfigDict, model_validatorfrom skyvern.config import settingsfrom skyvern.forge import appfrom skyvern.forge.sdk.db.enums import OrganizationAuthTokenType+from skyvern.forge.sdk.db.repositories.sms import SMSLifecycleLockTimeoutfrom skyvern.forge.sdk.encrypt.base import EncryptMethodfrom skyvern.forge.sdk.routes.sms_inbound import SMS_SIGNING_URL_UNAVAILABLEfrom skyvern.forge.sdk.schemas.organizations import (@@ -381,12 +382,15 @@ async def _finalize_phone_number(@asynccontextmanagerasync def _sms_lifecycle_lock(organization_id: str, phone_number: str | None = None) -> AsyncIterator[None]:- if phone_number is None:- async with app.DATABASE.sms.organization_lock(organization_id):- yield- else:- async with app.DATABASE.sms.lifecycle_lock(organization_id, normalize_phone_identifier(phone_number)):- yield+ try:+ if phone_number is None:+ async with app.DATABASE.sms.organization_lock(organization_id):+ yield+ else:+ async with app.DATABASE.sms.lifecycle_lock(organization_id, normalize_phone_identifier(phone_number)):+ yield+ except SMSLifecycleLockTimeout as exc:+ raise HTTPException(status_code=409, detail="SMS number operation is busy. Try again.") from exc@asynccontextmanagerdiff --git a/skyvern/forge/sdk/schemas/credentials.py b/skyvern/forge/sdk/schemas/credentials.pyindex f629776c9..58d903085 100644--- a/skyvern/forge/sdk/schemas/credentials.py+++ b/skyvern/forge/sdk/schemas/credentials.py@@ -331,6 +331,7 @@ class CredentialResponse(BaseModel):default=None,description="Opaque Skyvern-managed proxy sticky-session id.",)+ created_by: str | None = Field(default=None, description="ID of the user who created the credential")@field_validator("proxy_session_id")@classmethod@@ -440,6 +441,7 @@ class Credential(BaseModel):description="Opaque Skyvern-managed proxy sticky-session id.",)+ created_by: str | None = Field(default=None, description="ID of the user who created the credential")created_at: datetime = Field(..., description="Timestamp when the credential was created")modified_at: datetime = Field(..., description="Timestamp when the credential was last modified")deleted_at: datetime | None = Field(None, description="Timestamp when the credential was deleted, if applicable")diff --git a/skyvern/forge/sdk/schemas/persistent_browser_sessions.py b/skyvern/forge/sdk/schemas/persistent_browser_sessions.pyindex 1cafb5652..240937eb9 100644--- a/skyvern/forge/sdk/schemas/persistent_browser_sessions.py+++ b/skyvern/forge/sdk/schemas/persistent_browser_sessions.py@@ -107,6 +107,7 @@ class PersistentBrowserSession(BaseModel):close_requested_at: datetime | None = Nonecdp_unreachable_at: datetime | None = Noneclose_reason: str | None = None+ created_by: str | None = Nonecreated_at: datetimemodified_at: datetimedeleted_at: datetime | None = Nonediff --git a/skyvern/forge/sdk/schemas/sms.py b/skyvern/forge/sdk/schemas/sms.pyindex b4b827781..385955922 100644--- a/skyvern/forge/sdk/schemas/sms.py+++ b/skyvern/forge/sdk/schemas/sms.py@@ -12,7 +12,7 @@ from skyvern.utils.phone_validation import (normalize_phone_identifier,)-PhoneNumberStatus = Literal["active", "disabled", "released", "quarantined"]+PhoneNumberStatus = Literal["active", "disabled", "released", "quarantined", "provisioning"]PHONE_NUMBER_STATUSES: frozenset[str] = frozenset(get_args(PhoneNumberStatus))SMSConfigMode = Literal["connected", "manual", "managed"]SMS_CONFIG_MODES: frozenset[str] = frozenset(get_args(SMSConfigMode))@@ -49,6 +49,7 @@ class OrganizationPhoneNumber(BaseModel):price_cents: int | None = Nonestatus: PhoneNumberStatusquarantined_until: datetime | None = None+ provisioning_claimed_at: datetime | None = Nonecreated_at: datetimemodified_at: datetimedeleted_at: datetime | None = Nonediff --git a/skyvern/forge/sdk/services/credential/azure_credential_vault_service.py b/skyvern/forge/sdk/services/credential/azure_credential_vault_service.pyindex 549105d9e..08af0a709 100644--- a/skyvern/forge/sdk/services/credential/azure_credential_vault_service.py+++ b/skyvern/forge/sdk/services/credential/azure_credential_vault_service.py@@ -58,7 +58,12 @@ class AzureCredentialVaultService(CredentialVaultService):self._client = clientself._vault_name = vault_name- async def create_credential(self, organization_id: str, data: CreateCredentialRequest) -> Credential:+ async def create_credential(+ self,+ organization_id: str,+ data: CreateCredentialRequest,+ created_by: str | None = None,+ ) -> Credential:item_id = await self._create_azure_secret_item(organization_id=organization_id,credential=data.credential,@@ -69,6 +74,7 @@ class AzureCredentialVaultService(CredentialVaultService):data=data,item_id=item_id,vault_type=CredentialVaultType.AZURE_VAULT,+ created_by=created_by,)return credentialdiff --git a/skyvern/forge/sdk/services/credential/bitwarden_credential_service.py b/skyvern/forge/sdk/services/credential/bitwarden_credential_service.pyindex 74fa7e2db..197163002 100644--- a/skyvern/forge/sdk/services/credential/bitwarden_credential_service.py+++ b/skyvern/forge/sdk/services/credential/bitwarden_credential_service.py@@ -19,7 +19,12 @@ LOG = structlog.get_logger()class BitwardenCredentialVaultService(CredentialVaultService):- async def create_credential(self, organization_id: str, data: CreateCredentialRequest) -> Credential:+ async def create_credential(+ self,+ organization_id: str,+ data: CreateCredentialRequest,+ created_by: str | None = None,+ ) -> Credential:org_collection = await app.DATABASE.credentials.get_organization_bitwarden_collection(organization_id)if not org_collection:@@ -46,6 +51,7 @@ class BitwardenCredentialVaultService(CredentialVaultService):data=data,item_id=item_id,vault_type=CredentialVaultType.BITWARDEN,+ created_by=created_by,)return credentialdiff --git a/skyvern/forge/sdk/services/credential/credential_vault_service.py b/skyvern/forge/sdk/services/credential/credential_vault_service.pyindex a86a50b58..a1e7f45ee 100644--- a/skyvern/forge/sdk/services/credential/credential_vault_service.py+++ b/skyvern/forge/sdk/services/credential/credential_vault_service.py@@ -39,7 +39,12 @@ class CredentialVaultService(ABC):return None@abstractmethod- async def create_credential(self, organization_id: str, data: CreateCredentialRequest) -> Credential:+ async def create_credential(+ self,+ organization_id: str,+ data: CreateCredentialRequest,+ created_by: str | None = None,+ ) -> Credential:"""Create a new credential in the vault and database."""@abstractmethod@@ -263,6 +268,7 @@ class CredentialVaultService(ABC):data: CreateCredentialRequest,item_id: str,vault_type: CredentialVaultType,+ created_by: str | None = None,) -> Credential:if data.credential_type == CredentialType.PASSWORD:return await app.DATABASE.credentials.create_credential(@@ -280,6 +286,7 @@ class CredentialVaultService(ABC):tested_url=data.tested_url,proxy_location=data.proxy_location,proxy_session_id=data.proxy_session_id,+ created_by=created_by,)elif data.credential_type == CredentialType.CREDIT_CARD:return await app.DATABASE.credentials.create_credential(@@ -297,6 +304,7 @@ class CredentialVaultService(ABC):tested_url=data.tested_url,proxy_location=data.proxy_location,proxy_session_id=data.proxy_session_id,+ created_by=created_by,)elif data.credential_type == CredentialType.SECRET:return await app.DATABASE.credentials.create_credential(@@ -315,6 +323,7 @@ class CredentialVaultService(ABC):tested_url=data.tested_url,proxy_location=data.proxy_location,proxy_session_id=data.proxy_session_id,+ created_by=created_by,)else:raise Exception(f"Unsupported credential type: {data.credential_type}")diff --git a/skyvern/forge/sdk/services/credential/custom_credential_vault_service.py b/skyvern/forge/sdk/services/credential/custom_credential_vault_service.pyindex d518fc0d7..64e846b81 100644--- a/skyvern/forge/sdk/services/credential/custom_credential_vault_service.py+++ b/skyvern/forge/sdk/services/credential/custom_credential_vault_service.py@@ -126,7 +126,12 @@ class CustomCredentialVaultService(CredentialVaultService):return CustomCredentialAPIClient(api_base_url=config.api_base_url, api_token=config.api_token)- async def create_credential(self, organization_id: str, data: CreateCredentialRequest) -> Credential:+ async def create_credential(+ self,+ organization_id: str,+ data: CreateCredentialRequest,+ created_by: str | None = None,+ ) -> Credential:"""Create a new credential in the custom vault and database.@@ -161,6 +166,7 @@ class CustomCredentialVaultService(CredentialVaultService):data=data,item_id=item_id,vault_type=CredentialVaultType.CUSTOM,+ created_by=created_by,)except Exception:# Attempt to clean up the external credentialdiff --git a/skyvern/forge/sdk/services/credential/gcp_credential_vault_service.py b/skyvern/forge/sdk/services/credential/gcp_credential_vault_service.pyindex 79fe28230..357d7eaf1 100644--- a/skyvern/forge/sdk/services/credential/gcp_credential_vault_service.py+++ b/skyvern/forge/sdk/services/credential/gcp_credential_vault_service.py@@ -68,7 +68,12 @@ class GcpCredentialVaultService(CredentialVaultService):self._client = clientself._project_id = project_id- async def create_credential(self, organization_id: str, data: CreateCredentialRequest) -> Credential:+ async def create_credential(+ self,+ organization_id: str,+ data: CreateCredentialRequest,+ created_by: str | None = None,+ ) -> Credential:item_id = await self._create_gcp_secret_item(organization_id=organization_id,credential=data.credential,@@ -79,6 +84,7 @@ class GcpCredentialVaultService(CredentialVaultService):data=data,item_id=item_id,vault_type=CredentialVaultType.GCP,+ created_by=created_by,)return credentialdiff --git a/skyvern/forge/sdk/services/credential/skyvern_credential_vault_service.py b/skyvern/forge/sdk/services/credential/skyvern_credential_vault_service.pyindex 408165f6d..663a36584 100644--- a/skyvern/forge/sdk/services/credential/skyvern_credential_vault_service.py+++ b/skyvern/forge/sdk/services/credential/skyvern_credential_vault_service.py@@ -34,7 +34,12 @@ class SkyvernCredentialVaultService(CredentialVaultService):def __init__(self) -> None:self._fernet: Fernet | None = None- async def create_credential(self, organization_id: str, data: CreateCredentialRequest) -> Credential:+ async def create_credential(+ self,+ organization_id: str,+ data: CreateCredentialRequest,+ created_by: str | None = None,+ ) -> Credential:item_id = self._generate_item_id()item = CredentialItem(item_id=item_id,@@ -50,6 +55,7 @@ class SkyvernCredentialVaultService(CredentialVaultService):data=data,item_id=item_id,vault_type=CredentialVaultType.SKYVERN,+ created_by=created_by,)except BaseException:await self._reclaim_orphaned_vault_item(diff --git a/skyvern/forge/sdk/services/twilio_service.py b/skyvern/forge/sdk/services/twilio_service.pyindex b4d5105e7..07a88b187 100644--- a/skyvern/forge/sdk/services/twilio_service.py+++ b/skyvern/forge/sdk/services/twilio_service.py@@ -32,6 +32,7 @@ class TwilioClient:api_key_secret: str | None = None,auth_token: str | None = None,) -> None:+ """Create a client for an account or subaccount."""self.account_sid = account_sidself._username: strself._password: str | None@@ -42,6 +43,55 @@ class TwilioClient:self._username = account_sidself._password = auth_token+ async def create_subaccount(self, friendly_name: str) -> dict[str, Any]:+ url = f"{TWILIO_API_BASE}/{_TWILIO_API_VERSION}/Accounts.json"+ async with self._new_http_client() as client:+ return await self._request_json(+ client,+ "POST",+ url,+ data={"FriendlyName": friendly_name},+ )++ async def list_subaccounts(self, friendly_name: str) -> list[dict[str, Any]]:+ url = f"{TWILIO_API_BASE}/{_TWILIO_API_VERSION}/Accounts.json"+ async with self._new_http_client() as client:+ payload = await self._request_json(+ client,+ "GET",+ url,+ params={"FriendlyName": friendly_name, "Status": "active", "PageSize": "20"},+ )+ accounts = payload.get("accounts", [])+ if not isinstance(accounts, list) or not all(isinstance(account, dict) for account in accounts):+ raise TwilioApiError(200, "Twilio API returned an invalid account list")+ return accounts++ async def get_subaccount(self, account_sid: str) -> dict[str, Any]:+ url = f"{TWILIO_API_BASE}/{_TWILIO_API_VERSION}/Accounts/{account_sid}.json"+ async with self._new_http_client() as client:+ return await self._request_json(client, "GET", url)++ async def search_available_numbers(+ self,+ country_code: str = "US",+ area_code: str | None = None,+ contains: str | None = None,+ limit: int = 10,+ ) -> list[dict[str, Any]]:+ url = self._account_api_url(f"AvailablePhoneNumbers/{country_code}/Local.json")+ params = {"SmsEnabled": "true", "PageSize": str(limit)}+ if area_code is not None:+ params["AreaCode"] = area_code+ if contains is not None:+ params["Contains"] = contains+ async with self._new_http_client() as client:+ payload = await self._request_json(client, "GET", url, params=params)+ phone_numbers = payload.get("available_phone_numbers", [])+ if not isinstance(phone_numbers, list) or not all(isinstance(number, dict) for number in phone_numbers):+ raise TwilioApiError(200, "Twilio API returned an invalid available phone number list")+ return phone_numbers+def _new_http_client(self) -> httpx.AsyncClient:if self._password is None:raise TwilioApiError(0, "Twilio API credentials are incomplete")@@ -113,6 +163,31 @@ class TwilioClient:return phone_numbers+ async def purchase_number(+ self,+ phone_number: str,+ sms_url: str,+ sms_method: str = "POST",+ ) -> dict[str, Any]:+ url = self._account_api_url("IncomingPhoneNumbers.json")+ async with self._new_http_client() as client:+ return await self._request_json(+ client,+ "POST",+ url,+ data={"PhoneNumber": phone_number, "SmsUrl": sms_url, "SmsMethod": sms_method},+ )++ async def release_number(self, phone_number_sid: str) -> None:+ url = self._account_api_url(f"IncomingPhoneNumbers/{phone_number_sid}.json")+ async with self._new_http_client() as client:+ try:+ response = await client.request("DELETE", url)+ except httpx.HTTPError as exc:+ raise TwilioApiError(0, "Twilio API request failed") from exc+ if response.status_code != 204:+ raise TwilioApiError(response.status_code, _error_message(response))+async def get_incoming_phone_number(self, number_sid: str) -> dict[str, Any]:if not is_twilio_phone_number_sid(number_sid):raise ValueError("phone_number_sid must be a valid Twilio incoming phone number SID")diff --git a/skyvern/forge/sdk/workflow/models/web_search_block.py b/skyvern/forge/sdk/workflow/models/web_search_block.pyindex 2a0f68048..13b5019ad 100644--- a/skyvern/forge/sdk/workflow/models/web_search_block.py+++ b/skyvern/forge/sdk/workflow/models/web_search_block.py@@ -7,7 +7,7 @@ from collections.abc import Collectionfrom copy import deepcopyfrom dataclasses import dataclass, fieldfrom typing import Any, ClassVar, Literal, TypedDict-from urllib.parse import parse_qs, urlencode, urlsplit+from urllib.parse import SplitResult, parse_qs, urlencode, urlsplitimport structlogfrom jsonschema import Draft202012Validator@@ -28,6 +28,7 @@ from skyvern.schemas.workflows import (_normalize_outcome_error_code,_validate_no_match_error_code_prompt,)+from skyvern.utils.contained_effects import contained_effectfrom skyvern.utils.secret_redaction import redact_secrets_from_textLOG = structlog.get_logger()@@ -36,6 +37,41 @@ SearchProvider = Literal["google", "exa"]_PROMPT_OUTPUT_SCHEMA_ID = "urn:skyvern:web-search-prompt-output"+def _site_restriction(query: str) -> tuple[str, str] | None:+ if "OR" in query.split() or any(character in query for character in '|"“”()'):+ return None+ tokens = [+ token+ for token in query.split()+ if re.search(r"(?<!\w)site:", token, re.IGNORECASE) and not token.lower().startswith("-site:")+ ]+ if len(tokens) != 1 or not re.fullmatch(r"site:([a-z0-9-]+\.)+[a-z0-9-]+(/\S*)?", tokens[0], re.IGNORECASE):+ return None+ host, separator, path = tokens[0][5:].lower().partition("/")+ return host, separator + path if path else ""+++def _http_url(link: Any) -> SplitResult | None:+ try:+ parts = urlsplit(link) if isinstance(link, str) else None+ except ValueError:+ return None+ return parts if parts is not None and parts.scheme in {"http", "https"} and parts.hostname else None+++def _within_site(parts: SplitResult, restriction: tuple[str, str]) -> bool:+ host, path = restriction+ hostname = (parts.hostname or "").removesuffix(".")+ return (hostname == host or hostname.endswith("." + host)) and parts.path.lower().startswith(path)+++def _all_results_outside_site(items: Any, restriction: tuple[str, str]) -> bool:+ if not isinstance(items, list):+ return False+ urls = [url for item in items if isinstance(item, dict) and (url := _http_url(item.get("link"))) is not None]+ return bool(urls) and not any(_within_site(url, restriction) for url in urls)++def _wrap_prompt_schema(schema: dict[str, Any]) -> dict[str, Any]:output_schema = deepcopy(schema)if "$id" in output_schema:@@ -73,6 +109,7 @@ class SearchResponse:results: list[SearchResult] = field(default_factory=list)pages: list[dict[str, Any]] = field(default_factory=list)prompt_output: Any = None+ withheld_count: int = 0def output(self) -> dict[str, Any]:return {@@ -158,7 +195,9 @@ class WebSearchBlock(Block):raise WebSearchError(f"{provider.title()} search returned an invalid JSON response.")return self._redact_keys(body)- def _append_results(self, response: SearchResponse, items: Any, start: int = 0) -> None:+ def _append_results(+ self, response: SearchResponse, items: Any, start: int = 0, restriction: tuple[str, str] | None = None+ ) -> None:if not isinstance(items, list):raise WebSearchError(f"{response.provider.title()} search returned an invalid results list.")validated_results: list[SearchResult] = []@@ -172,12 +211,12 @@ class WebSearchBlock(Block):link = item.get("link") if response.provider == "google" else item.get("url")if not isinstance(link, str):raise WebSearchError(f"{response.provider.title()} search returned a result without a URL.")- try:- parsed = urlsplit(link)- if parsed.scheme not in {"http", "https"} or not parsed.hostname:- raise ValueError- except ValueError:- raise WebSearchError(f"{response.provider.title()} search returned an invalid result URL.") from None+ parsed = _http_url(link)+ if parsed is None:+ raise WebSearchError(f"{response.provider.title()} search returned an invalid result URL.")+ if restriction is not None and not _within_site(parsed, restriction):+ response.withheld_count += 1+ continueif link in seen:continueseen.add(link)@@ -196,7 +235,7 @@ class WebSearchBlock(Block):title=title if isinstance(title, str) else "",link=link,snippet=snippet if isinstance(snippet, str) else "",- display_link=display_link if isinstance(display_link, str) else parsed.hostname,+ display_link=display_link if isinstance(display_link, str) else (parsed.hostname or ""),position=start + index + 1,))@@ -206,31 +245,62 @@ class WebSearchBlock(Block):async def _google_search(self, response: SearchResponse) -> None:if not settings.SERPAPI_API_KEY:raise WebSearchError("Google search is not configured. Set SERPAPI_API_KEY on the server.")+ restriction = _site_restriction(response.query)+ refetches = 0+ refetch_stopped_reason = Nonestart = 0- for _ in range(10):- query = urlencode(- {"engine": "google", "q": response.query, "start": start, "api_key": settings.SERPAPI_API_KEY}- )- body = await self._request("google", f"https://serpapi.com/search.json?{query}")- response.pages.append(body)- metadata = body.get("search_metadata")- if not isinstance(metadata, dict) or metadata.get("status") != "Success":- raise WebSearchError("Google search did not complete successfully.")- items = body.get("organic_results", [])- self._append_results(response, items, start)- if not items or len(response.results) >= self.num_results:- return- pagination = body.get("serpapi_pagination")- next_page = pagination.get("next") if isinstance(pagination, dict) else None- if not isinstance(next_page, str):- return- try:- next_start = int(parse_qs(urlsplit(next_page).query)["start"][0])- except (KeyError, IndexError, ValueError):- raise WebSearchError("Google search returned invalid pagination metadata.") from None- if next_start <= start or next_start > 1000:- raise WebSearchError("Google search returned a non-advancing page offset.")- start = next_start+ try:+ for _ in range(10):+ params = {"engine": "google", "q": response.query, "start": start, "api_key": settings.SERPAPI_API_KEY}+ body = await self._request("google", f"https://serpapi.com/search.json?{urlencode(params)}")+ response.pages.append(body)+ metadata = body.get("search_metadata")+ if not isinstance(metadata, dict) or metadata.get("status") != "Success":+ raise WebSearchError("Google search did not complete successfully.")+ items = body.get("organic_results", [])+ outside_site = restriction is not None and _all_results_outside_site(items, restriction)+ while outside_site and refetches < 2:+ refetches += 1+ query = urlencode({**params, "no_cache": "true"})+ try:+ fresh_body = await self._request("google", f"https://serpapi.com/search.json?{query}")+ except Exception: # noqa: BLE001+ refetch_stopped_reason = "request_failed"+ break+ metadata = fresh_body.get("search_metadata")+ if not isinstance(metadata, dict) or metadata.get("status") != "Success":+ refetch_stopped_reason = "status_not_success"+ break+ body = fresh_body+ response.pages[-1] = body+ items = body.get("organic_results", [])+ outside_site = restriction is not None and _all_results_outside_site(items, restriction)+ if outside_site and refetches == 2 and refetch_stopped_reason is None:+ refetch_stopped_reason = "budget_spent"+ self._append_results(response, items, start, restriction)+ if outside_site or not items or len(response.results) >= self.num_results:+ return+ pagination = body.get("serpapi_pagination")+ next_page = pagination.get("next") if isinstance(pagination, dict) else None+ if not isinstance(next_page, str):+ return+ try:+ next_start = int(parse_qs(urlsplit(next_page).query)["start"][0])+ except (KeyError, IndexError, ValueError):+ raise WebSearchError("Google search returned invalid pagination metadata.") from None+ if next_start <= start or next_start > 1000:+ raise WebSearchError("Google search returned a non-advancing page offset.")+ start = next_start+ finally:+ if refetches > 0 or response.withheld_count > 0:+ with contained_effect("log Google search site restriction"):+ LOG.info(+ "Google search site restriction applied",+ refetches=refetches,+ withheld_count=response.withheld_count,+ results_returned=len(response.results),+ refetch_stopped_reason=refetch_stopped_reason,+ )async def _exa_search(self, response: SearchResponse) -> None:if not settings.EXA_API_KEY:diff --git a/skyvern/forge/taskv3/run_arms.py b/skyvern/forge/taskv3/run_arms.pyindex d867ff11a..5d0e6a62f 100644--- a/skyvern/forge/taskv3/run_arms.py+++ b/skyvern/forge/taskv3/run_arms.py@@ -18,6 +18,7 @@ LOG = structlog.get_logger()OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG = "TASK_V3_OBSERVE_DROP_OFFVIEWPORT_UNNAMED"TYPE_COORDINATE_CLICK_FLAG = "TASK_V3_TYPE_COORDINATE_CLICK"+DATE_SEGMENT_AIM_FLAG = "TASK_V3_DATE_SEGMENT_AIM"UNANSWERABLE_FIELD_REMEDY_FLAG = "TASK_V3_UNANSWERABLE_FIELD_REMEDY"REQUIRED_FIELD_ANSWERS_FLAG = "TASK_V3_REQUIRED_FIELD_ANSWERS"CUSTOMER_PRECEDENCE_FLAG = "TASK_V3_CUSTOMER_PRECEDENCE"diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.pyindex 3dc1332f9..f9e845373 100644--- a/skyvern/forge/taskv3/tools.py+++ b/skyvern/forge/taskv3/tools.py@@ -79,6 +79,7 @@ from skyvern.forge.taskv3.loop import ()from skyvern.forge.taskv3.preflight import PREFLIGHT_TOOL_NAMES, preflight_tool_actionfrom skyvern.forge.taskv3.run_arms import (+ DATE_SEGMENT_AIM_FLAG,OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG,TYPE_COORDINATE_CLICK_FLAG,run_arm_enabled,@@ -3893,6 +3894,19 @@ _MIRRORED_HOST_CONTROL_JS = (# which is a different question and the only one that separates these two cases: Playwright reports a# covered input as "visible, enabled, stable" and then fails the separate hit-target check, retrying# until the timeout.+# Every element a press can activate. `role` may carry a fallback list ("switch checkbox") in any ASCII+# case, so any interactive token makes it a control.+_INTERACTIVE_HIT_SEL = (+ 'a[href], button, input, select, textarea, [role~="button" i], [role~="link" i], [role~="checkbox" i], '+ '[role~="radio" i], [contenteditable]:not([contenteditable="false" i]), details, summary, iframe, embed, object, '+ "area[href], img[usemap], "+ 'video[controls], audio[controls], [role~="switch" i], [role~="menuitem" i], [role~="tab" i], '+ '[role~="option" i], [role~="combobox" i], [role~="textbox" i], [tabindex]:not([tabindex="-1"]), '+ '[onclick], [role~="slider" i], [role~="spinbutton" i], [role~="menuitemcheckbox" i], '+ '[role~="menuitemradio" i], [role~="treeitem" i], [role~="gridcell" i], [role~="searchbox" i], '+ '[role~="scrollbar" i], [draggable="true" i]'+)+_TYPE_TARGET_PROBE_JS = (r"""(arg) => {const _q = """@@ -4351,17 +4365,9 @@ _TYPE_TARGET_PROBE_JS = (let ctlRenderable = false;try { ctlRenderable = visible(ownLabelCtl, true); } catch (e) { ctlRenderable = false; }if (arg.allowOwnLabel !== false && boundaryVisible && ctlRenderable) {- // `role` may carry a fallback list ("switch checkbox") in any ASCII case; any interactive token makes- // it a control.- const INTERACTIVE_HIT_SEL =- 'a[href], button, input, select, textarea, [role~="button" i], [role~="link" i], [role~="checkbox" i], ' +- '[role~="radio" i], [contenteditable]:not([contenteditable="false" i]), details, summary, iframe, embed, object, ' +- 'area[href], img[usemap], ' +- 'video[controls], audio[controls], [role~="switch" i], [role~="menuitem" i], [role~="tab" i], ' +- '[role~="option" i], [role~="combobox" i], [role~="textbox" i], [tabindex]:not([tabindex="-1"]), ' +- '[onclick], [role~="slider" i], [role~="spinbutton" i], [role~="menuitemcheckbox" i], ' +- '[role~="menuitemradio" i], [role~="treeitem" i], [role~="gridcell" i], [role~="searchbox" i], ' +- '[role~="scrollbar" i], [draggable="true" i]';+ const INTERACTIVE_HIT_SEL = """+ + json.dumps(_INTERACTIVE_HIT_SEL)+ + r""";let interactiveDescendantHit = false;let layerOnTheWay = false;// A view-sized node anywhere in the hit chain up to the label is a backdrop wearing a label.@@ -4983,6 +4989,20 @@ _COLLATERAL_READBACK_JS = (}""")+# Which captured fields are segments of the tagged date group, so the moved-sibling report reads them by+# value or text and counts each once; the collateral take-back still covers every captured field.+_COLLATERAL_IS_DATE_SEGMENT_JS = (+ r"""(tags) => {+ const _q = """+ + _ROOT_QUERY_JS+ + r""";+ return tags.map((t) => {+ const f = _q.find('[data-tv3-collateral="' + t + '"]');+ return !!(f && f.hasAttribute('data-tv3-dateseg'));+ });+}"""+)+# Every text-holding field our keystrokes could reach if the widget routes them somewhere other than# the element we focused, tagged so each one can be read back by the same handle afterwards. Scoped to# the target's own form -- or its own root when it has none, which keeps a field inside a component@@ -5200,12 +5220,12 @@ _ANCHOR_LIST_SEMANTICS_JS = (# A segmented date input's group: the target must itself be a spinbutton whose own aria-label is# month/day/year -- not merely sitting near a group that has one, e.g. an unrelated ID spinbutton# sharing a fieldset with a real date group -- and its nearest fieldset/[role=group] ancestor (or,-# failing that, its plain parent) must contain exactly one editable spinbutton per month/day/year-# aria-label. Meaning comes from each segment's aria-label,+# failing that, its plain parent) must hold one editable spinbutton per label of a month/day/year date+# (with `arg.aim`, also a month/year or year-only date). Meaning comes from each segment's aria-label,# never DOM position, so a DD/MM/YYYY visual layout still resolves each component to the right-# segment. Tags the three winning elements data-tv3-dateseg="month"/"day"/"year" so the caller can-# address them individually; returns ok:false (and clears any stale tags) on anything short of a-# strict bijection, so a duplicate, missing, or readonly/disabled segment falls back to today's path.+# segment. Tags each segment data-tv3-dateseg="month"/"day"/"year" (with `arg.aim`, the group "group") so+# the caller can address them individually; returns ok:false (and clears any stale tags) on a duplicate, a+# readonly/disabled segment, or any other set of labels, which falls back to today's path._DATE_SEGMENT_GROUP_JS = (r"""(arg) => {const _q = """@@ -5253,9 +5273,13 @@ _DATE_SEGMENT_GROUP_JS = (order.push(lab);});if (duplicate) return { ok: false, reason: 'duplicate', targetLabel };- if (LABELS.some((l) => !found[l])) return { ok: false, reason: 'missing', targetLabel };+ const shape = LABELS.filter((l) => found[l]).map((l) => l[0]).join('');+ if ((arg.aim ? ['mdy', 'my', 'y'] : ['mdy']).indexOf(shape) === -1) {+ return { ok: false, reason: 'missing', targetLabel };+ }if (notEditable) return { ok: false, reason: 'not_editable', targetLabel };- LABELS.forEach((l) => found[l].setAttribute('data-tv3-dateseg', l));+ order.forEach((l) => found[l].setAttribute('data-tv3-dateseg', l));+ if (arg.aim) group.setAttribute('data-tv3-dateseg', 'group');return { ok: true, reason: null, targetLabel, order };}""")@@ -5269,6 +5293,40 @@ _DATE_SEGMENT_READBACK_JS = ("el => [el.value, el.textContent].filter(v => v != null && String(v).trim() !== '').join('|')")+# A press at a sub-pixel segment's centre reaches the hit and bubbles through every ancestor, so it may aim+# only when none of those is a control and nothing between the hit and the date group covers another segment.+_DATE_SEGMENT_AIM_JS = (+ r"""(el) => {+ const CONTROL = """+ + json.dumps(_INTERACTIVE_HIT_SEL + ", label")+ + r""";+ const centre = (e) => {+ const r = e.getBoundingClientRect();+ return [r.left + r.width / 2, r.top + r.height / 2];+ };+ const [x, y] = centre(el);+ const root = el.getRootNode();+ const hit = (root.elementsFromPoint ? root : document).elementsFromPoint(x, y)[0];+ if (!hit) return 'none';+ if (hit === el) return 'self';+ const group = el.closest('[data-tv3-dateseg="group"]');+ if (!group || !group.contains(hit) || hit === group) return 'outside';+ const others = Array.from(group.querySelectorAll('[data-tv3-dateseg]'))+ .filter((s) => s !== el && s !== group)+ .map(centre);+ for (let n = hit; n; n = n.parentElement || (n.getRootNode() && n.getRootNode().host) || null) {+ if (n.matches && n.matches(CONTROL)) return 'control';+ }+ for (let n = hit; n && n !== group; n = n.parentElement) {+ const box = n.getBoundingClientRect();+ if (others.some(([sx, sy]) => sx >= box.left && sx <= box.right && sy >= box.top && sy <= box.bottom)) {+ return 'other';+ }+ }+ return 'layer';+}"""+)+# Read back after a forced select_option so a styled proxy that silently didn't sync from its# native control is caught rather than reported as a successful selection._SELECT_READBACK_JS = (@@ -12690,7 +12748,9 @@ def build_browser_tools(async def _date_segment_group(page: Any, selector: str) -> dict[str, Any]:try:- probe = await page.evaluate(_DATE_SEGMENT_GROUP_JS, await _probe_arg(page, selector))+ probe = await page.evaluate(+ _DATE_SEGMENT_GROUP_JS, {**await _probe_arg(page, selector), "aim": _date_segment_aim_on()}+ )except Exception:return {"ok": False, "reason": None, "targetLabel": None}return probe if isinstance(probe, dict) else {"ok": False, "reason": None, "targetLabel": None}@@ -12729,37 +12789,69 @@ def build_browser_tools(# select-all chord wiped one real widget's whole render). Common widgets move focus to the# previous segment on a Backspace pressed while EMPTY, sending the next keys there, so stop once empty.try:- for _ in range(4):+ if not _date_segment_aim_on():+ for _ in range(4):+ if not _DATE_SEGMENT_DIGITS_RE.search(await _read_date_segment(page, selector)):+ return+ await locator.press("Backspace")+ return+ held = _DATE_SEGMENT_DIGITS_RE.search(await _read_date_segment(page, selector))+ if held:+ # A press leaves the caret where it landed, and Backspace deletes only what sits before it.+ if await locator.evaluate(_CARET_TO_END_JS, timeout=2000) == "end_key":+ await locator.press("End")+ for _ in range(len(held.group(0)) if held else 0):+ await locator.press("Backspace")if not _DATE_SEGMENT_DIGITS_RE.search(await _read_date_segment(page, selector)):return- await locator.press("Backspace")except Exception:pass- async def _type_one_date_segment(page: Any, selector: str, digits: str) -> bool:- locator = page.locator(selector).first- try:- await locator.scroll_into_view_if_needed(timeout=2000)- except Exception:- pass- # Some segment widgets move their section cursor only on a trusted pointer event, so focus()- # alone leaves the keys landing wherever that cursor already was. Click when the segment can- # actually take one -- gated on the same measurement Playwright's own viewport check uses, so- # a segment kept sub-pixel under its display layer is not made to spend a click's timeout- # being refused. Failures are swallowed: focus() below is what the write actually needs.+ def _date_segment_aim_on() -> bool:+ return run_arm_enabled(DATE_SEGMENT_AIM_FLAG, settings.TASK_V3_DATE_SEGMENT_AIM)++ async def _aim_date_segment(page: Any, selector: str, locator: Any, *, press: bool = True) -> str:+ # Some widgets move their section cursor only on a trusted pointer event and reset it when focus+ # enters the group, so focus() alone types into the wrong segment; a sub-pixel one is pressed through its layer.try:box = await locator.bounding_box(timeout=2000)except Exception:box = None- if box and box["width"] * box["height"] > 1:+ if not box:+ return "focus"+ if box["width"] * box["height"] > 1:+ if not press:+ return "click"try:await locator.click(timeout=2000)except Exception:- pass+ return "focus"+ return "click"+ # A press in a child frame lands wherever the top page paints at that point, which the hit test+ # inside the frame cannot see, so a framed segment is only focused.+ if not _date_segment_aim_on() or (_acted_realm and page.parent_frame is not None):+ return "focus"+ try:+ hit = await locator.evaluate(_DATE_SEGMENT_AIM_JS, timeout=2000)+ except Exception:+ hit = None+ if hit != "layer":+ return "focus"+ if not press:+ return "mirror"+ return "mirror" if await _click_at_box_centre(page, selector) else "focus"++ async def _type_one_date_segment(page: Any, selector: str, digits: str) -> tuple[bool, str]:+ locator = page.locator(selector).first+ try:+ await locator.scroll_into_view_if_needed(timeout=2000)+ except Exception:+ pass+ aim = await _aim_date_segment(page, selector, locator)try:await locator.focus(timeout=2000)except Exception:- return False+ return False, aimawait _clear_date_segment(page, selector, locator)# locator.fill() does not commit digits into a date spinbutton segment; only real keystrokes# advance it, so this and the element-focused fallback below both TYPE rather than fill.@@ -12768,14 +12860,30 @@ def build_browser_tools(except Exception:passif await _date_segment_holds(page, selector, digits):- return True+ return True, aimtry:+ if _date_segment_aim_on():+ aim = await _aim_date_segment(page, selector, locator)await locator.focus(timeout=2000)await _clear_date_segment(page, selector, locator)await locator.press_sequentially(digits, delay=40)except Exception:- return False- return await _date_segment_holds(page, selector, digits)+ return False, aim+ return await _date_segment_holds(page, selector, digits), aim++ def _date_group_shape(labels: list[str]) -> str:+ return "".join(label[0] for label in _DATE_SEGMENT_ORDER if label in labels)++ async def _collateral_outside_date_segments(page: Any, captured: list[list[str]]) -> list[list[str]]:+ if not captured:+ return captured+ try:+ flags = await page.evaluate(_COLLATERAL_IS_DATE_SEGMENT_JS, [e[0] for e in captured if len(e) == 2])+ except Exception:+ return captured+ if not isinstance(flags, list) or len(flags) != len(captured):+ return captured+ return [entry for entry, is_segment in zip(captured, flags, strict=False) if not is_segment]async def _drifted_date_segment(page: Any, written: list[tuple[str, str, str]]) -> str | None:# The segment typed last still holds focus, so a widget that normalizes or clamps a segment's@@ -12793,12 +12901,36 @@ def build_browser_tools(return labelreturn None- async def _fill_date_segment_group(page: Any, selector: str, components: dict[str, str]) -> ToolResult:+ async def _fill_date_segment_group(+ page: Any, selector: str, components: dict[str, str], order: list[str]+ ) -> ToolResult:written: list[tuple[str, str, str]] = []- for label in _DATE_SEGMENT_ORDER:+ arm = _date_segment_aim_on()+ write_order = list(_DATE_SEGMENT_ORDER)+ if arm:+ # A segment that can only be focused types wherever the widget's cursor is, which a widget+ # resets to its first segment, so without a press on every segment the group is written in+ # its own order.+ for label in order:+ segment_selector = f'[data-tv3-dateseg="{label}"]'+ aimable = await _aim_date_segment(+ page, segment_selector, page.locator(segment_selector).first, press=False+ )+ if aimable == "focus":+ write_order = list(order)+ break+ for label in write_order:segment_selector = f'[data-tv3-dateseg="{label}"]'- committed = await _type_one_date_segment(page, segment_selector, components[label])- LOG.info("taskv3 date segment fill", segment=label, committed=committed, whole_date=True)+ committed, aim = await _type_one_date_segment(page, segment_selector, components[label])+ LOG.info(+ "taskv3 date segment fill",+ segment=label,+ committed=committed,+ whole_date=True,+ aim=aim,+ group_shape=_date_group_shape(order),+ date_segment_aim_arm=arm,+ )if not committed:return ToolResult.error(f"typed a date into {selector}'s segmented date field, but the {label} segment did not "@@ -12829,21 +12961,45 @@ def build_browser_tools(return _covered_error(selector, occluder)return None- async def _fill_one_date_segment(page: Any, selector: str, label: str, digits: str) -> ToolResult:+ async def _fill_one_date_segment(+ page: Any, selector: str, label: str, digits: str, labels: list[str], *, text_is_secret: bool+ ) -> ToolResult:# Addressed through the tag the probe just wrote, exactly as the group fill is: that is the# element the probe established is this segment, where re-resolving the caller's selector# would act on whatever it matches now.segment_selector = f'[data-tv3-dateseg="{label}"]'+ siblings = [other for other in labels if other != label]++ async def moved_segments(before_siblings: dict[str, str]) -> int:+ # Read by value or text, so a segment rendered as text is counted when it moves too.+ now = {other: await _read_date_segment(page, f'[data-tv3-dateseg="{other}"]') for other in siblings}+ return sum(now[other] != before_siblings[other] for other in siblings)+# Exactly one segment is being written, so a sibling that moves while the keys are sent took# them by misrouting and is owed them back -- the same repair the plain path performs, which# this path would otherwise drop. The group fill cannot reuse it: writing its siblings is the# job there, so their movement is indistinguishable from a misroute.+ arm = _date_segment_aim_on()before = await _read_date_segment(page, segment_selector)+ before_siblings = (+ {other: await _read_date_segment(page, f'[data-tv3-dateseg="{other}"]') for other in siblings}+ if arm+ else {}+ )collateral = await _capture_collateral(page, segment_selector)- committed = await _type_one_date_segment(page, segment_selector, digits)+ outside = await _collateral_outside_date_segments(page, collateral) if arm else []+ committed, aim = await _type_one_date_segment(page, segment_selector, digits)moved = await _collateral_moved_while_typing(page, collateral) if collateral else []+ moved_outside = await _collateral_moved_while_typing(page, outside) if outside else []LOG.info(- "taskv3 date segment fill", segment=label, committed=committed, whole_date=False, siblings_moved=len(moved)+ "taskv3 date segment fill",+ segment=label,+ committed=committed,+ whole_date=False,+ siblings_moved=await moved_segments(before_siblings) + len(moved_outside) if arm else len(moved),+ aim=aim,+ group_shape=_date_group_shape(labels),+ date_segment_aim_arm=arm,)if not committed:# Ownership is decided exactly as the plain path decides it: the keys are ours to take back@@ -12853,27 +13009,41 @@ def build_browser_tools(held = await _read_date_segment(page, segment_selector)if moved and (not held or held == before):await _restore_collateral(page, moved)+ reach = (+ " It could only be focused, not clicked, so the widget may have sent the keys elsewhere."+ if arm and aim == "focus"+ else ""+ )return ToolResult.error(f"typed into {selector}, but its {label} segment did not commit the value afterward -- "- "the field is NOT filled. Re-observe and retry."+ f"the field is NOT filled.{reach} Re-observe and retry.")if await _drifted_date_segment(page, [(label, segment_selector, digits)]) is not None:- return ToolResult.error(- f"typed into {selector}'s {label} segment, but it changed afterward, so the segment may now "- "hold a different value than requested. The page changed it, and it was left as the page set "- "it. Re-observe it to see what value the field holds.",- error_class="value_changed_by_page",+ if not arm:+ return ToolResult.error(+ f"typed into {selector}'s {label} segment, but it changed afterward, so the segment may now "+ "hold a different value than requested. The page changed it, and it was left as the page "+ "set it. Re-observe it to see what value the field holds.",+ error_class="value_changed_by_page",+ )+ now = _DATE_SEGMENT_DIGITS_RE.search(await _read_date_segment(page, segment_selector))+ return await _value_changed_by_page_error(+ page, selector, digits, now.group(0) if now else "", echo=not text_is_secret)# Read the siblings a second time, because the blur above is itself an event a widget derives# or clamps another component on -- and that fires after the read the restore decision used,# which has to stay next to the keystrokes to be able to attribute them.- settled = await _collateral_moved_while_typing(page, collateral) if collateral else moved- if settled:+ if arm:+ settled_outside = await _collateral_moved_while_typing(page, outside) if outside else []+ changed = await moved_segments(before_siblings) + len(settled_outside)+ else:+ changed = len(await _collateral_moved_while_typing(page, collateral) if collateral else moved)+ if changed:# The keys landed in the segment, so by the ownership rule above these other fields are# not ours to take back -- but they did move, and saying so is the tool reporting what# happened rather than deciding whether it matters.return ToolResult.ok(- f"typed into {selector}; filled its {label} segment. {len(settled)} other field(s) in "+ f"typed into {selector}; filled its {label} segment. {changed} other field(s) in ""the same group changed while it was typed -- re-observe the date before relying on it")return ToolResult.ok(f"typed into {selector}; filled its {label} segment")@@ -12905,9 +13075,17 @@ def build_browser_tools(parsed_date is not None or _DATE_SEGMENT_TEXT_RE.fullmatch(text.strip())) and await _declares_spinbutton_role(page, selector) is not False:group = await _date_segment_group(page, selector)+ order = group.get("order")+ labels = [+ label for label in (order if isinstance(order, list) else []) if label in _DATE_SEGMENT_ORDER+ ] or list(_DATE_SEGMENT_ORDER)if group.get("ok"):+ # A whole date needs all three segments; a month/year or year-only group takes one+ # component at a time.date_components = (- _resolve_date_components(parsed_date, group.get("order")) if parsed_date is not None else None+ _resolve_date_components(parsed_date, order)+ if parsed_date is not None and len(labels) == len(_DATE_SEGMENT_ORDER)+ else None)target_label = str(group.get("targetLabel") or "")segment_digits = (@@ -12917,12 +13095,19 @@ def build_browser_tools(blocked = await _date_segment_write_blocked(page, selector)if blocked is not None:return blocked- return await _fill_date_segment_group(page, selector, date_components)+ return await _fill_date_segment_group(page, selector, date_components, labels)if segment_digits is not None:blocked = await _date_segment_write_blocked(page, selector)if blocked is not None:return blocked- return await _fill_one_date_segment(page, selector, target_label, segment_digits)+ return await _fill_one_date_segment(+ page,+ selector,+ target_label,+ segment_digits,+ labels,+ text_is_secret=text != args.get("text", ""),+ )# A typeahead silently rejects raw typed text — it only accepts a picked suggestion — and the# model does not reliably reach for select_combobox on its own. So after typing into a plain text# field, check whether the page REACTED with a suggestion list and, if so, commit the best matchdiff --git a/skyvern/webeye/default_persistent_sessions_manager.py b/skyvern/webeye/default_persistent_sessions_manager.pyindex b56dcc039..0201dd552 100644--- a/skyvern/webeye/default_persistent_sessions_manager.py+++ b/skyvern/webeye/default_persistent_sessions_manager.py@@ -665,6 +665,7 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):queue_deadline_epoch_ms: int | None = None,workflow_run_id: str | None = None,*,+ created_by: str | None = None,attempt_number: int | None = None,dispatch_claim_started_at: datetime | None = None,expected_browser_session_id: str | None = None,@@ -694,6 +695,7 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):bound_workflow_permanent_id=bound_workflow_permanent_id,bound_key=bound_key,download_run_id=resolve_run_download_id(skyvern_context.current(), fallback_run_id=runnable_id),+ created_by=created_by,)except BaseException as error:# A failed acknowledgement does not prove the committed session is an orphan.diff --git a/skyvern/webeye/persistent_sessions_manager.py b/skyvern/webeye/persistent_sessions_manager.pyindex 46dd2f8f6..c3238aceb 100644--- a/skyvern/webeye/persistent_sessions_manager.py+++ b/skyvern/webeye/persistent_sessions_manager.py@@ -203,6 +203,7 @@ class PersistentSessionsManager(Protocol):queue_deadline_epoch_ms: int | None = None,workflow_run_id: str | None = None,*,+ created_by: str | None = None,attempt_number: int | None = None,dispatch_claim_started_at: datetime | None = None,expected_browser_session_id: str | None = None,diff --git a/skyvern/webeye/schemas.py b/skyvern/webeye/schemas.pyindex 607b25949..2b5ba7cad 100644--- a/skyvern/webeye/schemas.py+++ b/skyvern/webeye/schemas.py@@ -86,6 +86,7 @@ class BrowserSessionResponse(BaseModel):recordings: list[FileInfo] | None = Field(None, description="The list of video recordings from the browser session")started_at: datetime | None = Field(None, description="Timestamp when the session was started")completed_at: datetime | None = Field(None, description="Timestamp when the session was completed")+ created_by: str | None = Field(None, description="ID of the user who created the session")created_at: datetime = Field(description="Timestamp when the session was created (the timestamp for the initial request)")@@ -219,4 +220,5 @@ class BrowserSessionResponse(BaseModel):browser_type=browser_session.browser_type,browser_profile_id=browser_session.browser_profile_id,generate_browser_profile=browser_session.generate_browser_profile,+ created_by=browser_session.created_by,)diff --git a/tests/unit/forge/sdk/routes/test_browser_sessions.py b/tests/unit/forge/sdk/routes/test_browser_sessions.pyindex 1772c260e..44a01240f 100644--- a/tests/unit/forge/sdk/routes/test_browser_sessions.py+++ b/tests/unit/forge/sdk/routes/test_browser_sessions.py@@ -7,10 +7,15 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom fastapi import HTTPExceptionfrom fastapi.responses import ORJSONResponse+from sqlalchemy.ext.asyncio import AsyncEnginefrom skyvern.exceptions import BrowserSessionExtensionUnconfirmed, BrowserSessionNotExtendable+from skyvern.forge import app as forge_app+from skyvern.forge.agent_functions import AgentFunction+from skyvern.forge.sdk.db.agent_db import AgentDBfrom skyvern.forge.sdk.routes import browser_sessions as browser_sessions_modfrom skyvern.schemas.browser_session_timeouts import max_lifetime_exceeded_warning+from skyvern.webeye.default_persistent_sessions_manager import DefaultPersistentSessionsManagerfrom skyvern.webeye.persistent_sessions_manager import (BrowserSessionCreditAdmissionRefusal,BrowserSessionExtension,@@ -251,3 +256,24 @@ async def test_get_browser_session_enables_strict_download_lookup() -> None:fail_download_lookup=True,include_stream_transport=True,)+++async def test_create_browser_session_records_the_caller_as_creator(+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: AsyncEngine+) -> None:+ db = AgentDB("sqlite+aiosqlite:///:memory:", db_engine=sqlite_engine)+ org = await db.organizations.create_organization(organization_name="Creator Org")+ monkeypatch.setattr(forge_app.DATABASE, "browser_sessions", db.browser_sessions)+ monkeypatch.setattr(forge_app, "PERSISTENT_SESSIONS_MANAGER", DefaultPersistentSessionsManager(database=db))+ monkeypatch.setattr(forge_app, "AGENT_FUNCTION", AgentFunction())+ monkeypatch.setattr(forge_app, "STORAGE", None)++ await browser_sessions_mod.create_browser_session(+ browser_sessions_mod.CreateBrowserSessionRequest(),+ current_org=org,+ user_id="user_creator",+ )+ [listed] = await browser_sessions_mod.get_browser_sessions_all(current_org=org, page=1, page_size=10)++ assert listed.created_by == "user_creator"diff --git a/tests/unit/forge/sdk/routes/test_debug_sessions.py b/tests/unit/forge/sdk/routes/test_debug_sessions.pyindex 12b399acf..7c4a41540 100644--- a/tests/unit/forge/sdk/routes/test_debug_sessions.py+++ b/tests/unit/forge/sdk/routes/test_debug_sessions.py@@ -42,6 +42,7 @@ async def test_prewarm_debug_session_dispatches_an_unattached_live_browser() ->runnable_type=debug_sessions_mod.PREWARM_PENDING_RUNNABLE_TYPE,wait_for_startup=False,needs_live_view=True,+ created_by="user_123",)app_mock.DATABASE.browser_sessions.mark_prewarm_dispatched.assert_awaited_once_with(session_id="pbs_prewarm",@@ -533,6 +534,7 @@ async def test_new_debug_session_uses_workflow_proxy_default_for_created_browserwait_for_startup=False,# A debug session exists to be watched in the studio, so it always declares it.needs_live_view=True,+ created_by="user_123",)app_mock.DATABASE.debug.create_debug_session.assert_awaited_once_with(browser_session_id="pbs_new",diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.pyindex 88c0d8aac..e73623533 100644--- a/tests/unit/test_agent_task_v3.py+++ b/tests/unit/test_agent_task_v3.py@@ -76,6 +76,7 @@ from skyvern.forge.taskv3.loop import ()from skyvern.forge.taskv3.run_arms import (CUSTOMER_PRECEDENCE_FLAG,+ DATE_SEGMENT_AIM_FLAG,EXTRACTION_REPORTS_FLAG,NO_ACTION_HOLD_FLAG,OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG,@@ -179,6 +180,7 @@ async def _run_execute_task_v3(OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG, forced=False)loop_mock.type_coordinate_click_enabled_during_loop = run_arm_enabled(TYPE_COORDINATE_CLICK_FLAG, forced=False)+ loop_mock.date_segment_aim_enabled_during_loop = run_arm_enabled(DATE_SEGMENT_AIM_FLAG, forced=False)loop_mock.unanswerable_field_remedy_during_loop = run_arm_enabled(UNANSWERABLE_FIELD_REMEDY_FLAG, forced=False)loop_mock.required_field_answers_during_loop = run_arm_enabled(REQUIRED_FIELD_ANSWERS_FLAG, forced=False)loop_mock.customer_precedence_during_loop = run_arm_enabled(CUSTOMER_PRECEDENCE_FLAG, forced=False)@@ -388,6 +390,31 @@ async def test_execute_task_v3_buckets_the_type_coordinate_click_arm_per_run(mon)+async def test_execute_task_v3_buckets_the_date_segment_aim_arm_per_run(monkeypatch: pytest.MonkeyPatch) -> None:+ # Without the resolve call every run reads the arm off; bucketed by workflow run like its siblings.+ monkeypatch.setattr(settings, "TASK_V3_DATE_SEGMENT_AIM", False)+ provider = AsyncMock(return_value="treatment")+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "get_value_cached", provider)++ outcome = LoopOutcome(status="completed", reason="done", billable_actions=[])+ _step, task, loop_mock, _post = await _run_execute_task_v3(+ monkeypatch,+ outcome,+ workflow_run_id="wr_date_segment_aim",+ data_extraction_goal=None,+ extracted_information_schema=None,+ )++ assert loop_mock.date_segment_aim_enabled_during_loop is True+ assert loop_mock.context.run_arms[DATE_SEGMENT_AIM_FLAG] == (task.workflow_run_id, "treatment")+ provider.assert_any_await(+ DATE_SEGMENT_AIM_FLAG,+ task.workflow_run_id,+ properties={"organization_id": task.organization_id},+ )++@pytest.mark.asyncioasync def test_execute_task_v3_resolves_the_unanswerable_field_remedy_arm_before_the_loop_reads_it(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_browser_session_profile_export_gate.py b/tests/unit/test_browser_session_profile_export_gate.pyindex 45c996d78..e76e51c9f 100644--- a/tests/unit/test_browser_session_profile_export_gate.py+++ b/tests/unit/test_browser_session_profile_export_gate.py@@ -74,6 +74,7 @@ async def test_create_browser_session_passes_start_url_to_session_manager() -> Ngenerate_browser_profile=True,),current_org=SimpleNamespace(organization_id="org_1"),+ user_id="user_1",)assert result is response@@ -88,6 +89,7 @@ async def test_create_browser_session_passes_start_url_to_session_manager() -> Nbrowser_profile_id=None,generate_browser_profile=True,needs_live_view=False,+ created_by="user_1",)from_browser_session.assert_awaited_once_with(created_session)diff --git a/tests/unit/test_credential_update_params.py b/tests/unit/test_credential_update_params.pyindex 0e45681b9..8ad5eac1d 100644--- a/tests/unit/test_credential_update_params.py+++ b/tests/unit/test_credential_update_params.py@@ -2,16 +2,20 @@on CredentialRepository."""from datetime import datetime+from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom fastapi import BackgroundTasks, HTTPExceptionfrom pydantic import ValidationError+from sqlalchemy.ext.asyncio import AsyncEngine+from skyvern.config import settingsfrom skyvern.forge import app as forge_appfrom skyvern.forge.agent_functions import AgentFunctionfrom skyvern.forge.forge_app import ForgeApp+from skyvern.forge.sdk.db.agent_db import AgentDBfrom skyvern.forge.sdk.db.repositories.browser_sessions import BrowserSessionsRepositoryfrom skyvern.forge.sdk.db.repositories.credentials import CredentialRepositoryfrom skyvern.forge.sdk.routes import credentials as credentials_routes@@ -31,6 +35,7 @@ from skyvern.forge.sdk.schemas.credentials import (UpdateCredentialRequest,)from skyvern.forge.sdk.services.credential.credential_vault_service import CredentialVaultService+from skyvern.forge.sdk.services.credential.skyvern_credential_vault_service import SkyvernCredentialVaultServicefrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatusfrom skyvern.schemas.proxy_pinning import apply_proxy_pin_update as _apply_proxy_pin_updatefrom skyvern.schemas.proxy_pinning import (@@ -1831,3 +1836,35 @@ def test_login_test_request_accepts_empty_password() -> None:assert LoginTestRequest(url="https://example.com/login", username="[email protected]").password == ""with pytest.raises(ValidationError):LoginTestRequest(url="https://example.com/login", username="", password="")+++async def test_create_credential_records_the_caller_as_creator(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, sqlite_engine: AsyncEngine+) -> None:+ db = AgentDB("sqlite+aiosqlite:///:memory:", db_engine=sqlite_engine)+ org = await db.organizations.create_organization(organization_name="Creator Org")+ monkeypatch.setattr(settings, "LOCAL_CREDENTIAL_VAULT_PATH", str(tmp_path))+ monkeypatch.setattr(settings, "LOCAL_CREDENTIAL_VAULT_KEY", None)+ monkeypatch.setattr(forge_app.DATABASE, "credentials", db.credentials)+ monkeypatch.setattr(+ credentials_routes,+ "_get_credential_vault_service",+ AsyncMock(return_value=SkyvernCredentialVaultService()),+ )++ await credentials_routes.create_credential(+ background_tasks=BackgroundTasks(),+ data=CreateCredentialRequest(+ name="Login",+ credential_type=CredentialType.PASSWORD,+ credential={"username": "[email protected]", "password": "pw"},+ ),+ current_org=org,+ current_user_id="user_creator",+ )+ [listed] = await credentials_routes.get_credentials(+ current_org=org, page=1, page_size=10, vault_type=None, credential_type=None, search=None, folder_id=None+ )++ assert listed.created_by == "user_creator"diff --git a/tests/unit/test_twilio_integration_routes.py b/tests/unit/test_twilio_integration_routes.pyindex 282de07f9..98dbca1e1 100644--- a/tests/unit/test_twilio_integration_routes.py+++ b/tests/unit/test_twilio_integration_routes.py@@ -258,6 +258,16 @@ async def test_postgres_lifecycle_permit_reserves_pool_connection_for_repositorydef get_bind(self) -> SimpleNamespace:return engine+ async def connection(self) -> None:+ pass++ async def scalar(self, statement: object, params: object) -> bool:+ lock = database_locks.setdefault(str(params["lock_key"]), asyncio.Lock())+ if lock.locked():+ return False+ await lock.acquire()+ return True+async def execute(self, statement: object, params: object) -> None:lock_key = str(params["lock_key"]) # type: ignore[index]lock = database_locks.setdefault(lock_key, asyncio.Lock())@@ -785,7 +795,9 @@ def _inbound_database(or AsyncMock(return_value=SimpleNamespace(totp_code_id="otp_short")),create_raw_otp_code_if_new=create_raw_otp_code_if_newor AsyncMock(return_value=SimpleNamespace(totp_code_id="otp_raw")),+ promote_raw_otp_code=AsyncMock(),)+ database.sms.get_sms_config_signing_token.return_value = Nonereturn database@@ -832,7 +844,10 @@ def test_connected_inbound_requires_configured_base_url(client: TestClient, monkeypatch: pytest.MonkeyPatch, base_url: str) -> None:database = _inbound_database(- mode="connected", twilio_token=SimpleNamespace(credential=SimpleNamespace(auth_token=_TWILIO_AUTH_TOKEN))+ mode="connected",+ twilio_token=SimpleNamespace(+ credential=TwilioCredential(account_sid=ACCOUNT_SID, auth_token=_TWILIO_AUTH_TOKEN)+ ),)monkeypatch.setattr(sms_inbound.settings, "SKYVERN_BASE_URL", base_url)log = Mock()@@ -955,7 +970,9 @@ async def test_valid_ingest_promotes_stored_raw_row_and_returns_xml(database = _inbound_database(mode="connected",phone_number=_inbound_phone_number(status=phone_status),- twilio_token=SimpleNamespace(credential=SimpleNamespace(auth_token=_TWILIO_AUTH_TOKEN)),+ twilio_token=SimpleNamespace(+ credential=TwilioCredential(account_sid=ACCOUNT_SID, auth_token=_TWILIO_AUTH_TOKEN)+ ),)database.otp = agent_db.otpraw_ids: list[str] = []@@ -1013,8 +1030,26 @@ def test_managed_config_fails_closed_until_persisted_signing_contract(api_key_secret="api-key-secret",)),+ SimpleNamespace(+ credential=TwilioCredential(+ account_sid=ACCOUNT_SID,+ api_key_sid=API_KEY_SID,+ api_key_secret="api-key-secret",+ auth_token=None,+ )+ ),+ SimpleNamespace(credential=None),+ SimpleNamespace(credential=SimpleNamespace()),+ SimpleNamespace(credential=SimpleNamespace(account_sid=ACCOUNT_SID, auth_token=None)),+ ],+ ids=[+ "missing-auth-token",+ "typed-credential-without-auth-token",+ "typed-credential-with-explicit-null-auth-token",+ "null-credential",+ "missing-auth-token-attribute",+ "credential-without-auth-token",],- ids=["missing-auth-token", "credential-without-auth-token"],)def test_connected_config_fails_closed_without_auth_token(client: TestClient,@@ -1030,6 +1065,7 @@ def test_connected_config_fails_closed_without_auth_token(assert response.status_code == 403database.organizations.get_valid_org_auth_token.assert_awaited_once()database.sms.get_phone_number_by_number.assert_not_awaited()+ database.otp.create_raw_otp_code_if_new.assert_not_awaited()@pytest.mark.parametrize(@@ -1352,6 +1388,7 @@ def test_password_response_exposes_seed_presence_without_secret() -> None:folder_id=None,proxy_location=None,proxy_session_id=None,+ created_by=None,)response = credentials._convert_to_response(credential).model_dump()@@ -1435,3 +1472,133 @@ class TestCredentialVaultLegacySeedPreservation:service.get_credential_item.assert_not_awaited()assert service._update_db_credential.await_args.kwargs["data"] is requestassert "totp" not in service._update_db_credential.await_args.kwargs["data"].credential.model_fields_set++[email protected]("valid", [True, False])+def test_managed_inbound_signing_token(client: TestClient, monkeypatch: pytest.MonkeyPatch, valid: bool) -> None:+ database = _inbound_database(mode="managed")+ database.sms.get_sms_config_signing_token.return_value = "managed-secret"+ base_url = "https://api.example.test"+ monkeypatch.setattr(sms_inbound.settings, "SKYVERN_BASE_URL", base_url)+ form = _inbound_form(body="123456")+ signature = compute_twilio_signature(+ "managed-secret", build_inbound_sms_url(base_url, _SMS_CONFIG_ID, _WEBHOOK_SECRET), form+ )+ response = _post_inbound(client, monkeypatch, database, form=form, signature=signature if valid else "bad")+ assert response.status_code == (200 if valid else 400)+ assert database.otp.create_otp_code_if_new.await_count == int(valid)++[email protected]("invalid_on_read", [False, True])+def test_unknown_inbound_mode_fails_closed(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, invalid_on_read: bool+) -> None:+ database = _inbound_database(mode="unknown")+ if invalid_on_read:+ with pytest.raises(ValidationError) as error:+ _config("unknown")+ database.sms.get_sms_config_with_secret_for_inbound.side_effect = error.value+ log = Mock()+ monkeypatch.setattr(sms_inbound, "LOG", log)+ response = _post_inbound(client, monkeypatch, database)+ assert response.status_code == 403+ log.error.assert_called_once()+ database.otp.create_otp_code_if_new.assert_not_awaited()++[email protected]("stage", ["permit", "checkout", "advisory"])[email protected]("cancel", [False, True])+async def test_postgres_lock_acquisition_deadline_and_cancellation(monkeypatch, stage, cancel):+ from contextlib import asynccontextmanager++ from skyvern.forge.sdk.db.repositories import sms as module++ monkeypatch.setattr(module, "LIFECYCLE_LOCK_TIMEOUT_SECONDS", 0.05)+ waiting = asyncio.Event()+ calls = []++ async def wait_forever():+ waiting.set()+ await asyncio.Event().wait()++ async def scalar(statement, params):+ calls.append(params["lock_key"])+ if len(calls) == 1:+ return True+ await wait_forever()++ session = SimpleNamespace(+ get_bind=lambda: SimpleNamespace(dialect=SimpleNamespace(name="postgresql")),+ connection=AsyncMock(side_effect=wait_forever if stage == "checkout" else None),+ scalar=AsyncMock(side_effect=scalar),+ invalidate=AsyncMock(),+ )++ @asynccontextmanager+ async def session_factory():+ yield session++ @asynccontextmanager+ async def permit():+ if stage == "permit":+ await wait_forever()+ yield++ repository = SMSRepository(session_factory)+ monkeypatch.setattr(repository, "_lifecycle_permit", permit)++ async def acquire():+ async with repository.lifecycle_lock("org", "+14155552671"):+ pytest.fail("acquired contended resource")++ task = asyncio.create_task(acquire())+ await waiting.wait()+ if cancel:+ task.cancel()+ with pytest.raises(asyncio.CancelledError if cancel else module.SMSLifecycleLockTimeout):+ await task+ assert session.invalidate.await_count == int(stage != "permit")+ if stage == "advisory":+ assert len(calls) == 2+++ ("method", "path", "payload"),+ [+ ("POST", "/phone-numbers/enable", {"phone_number_sid": "PN0123456789abcdef0123456789abcdef"}),+ ("POST", "/phone-numbers/disable", {"phone_number_id": "pn_existing"}),+ (+ "POST",+ "/credentials",+ {"credential": {"account_sid": ACCOUNT_SID, "auth_token": "token"}},+ ),+ ("DELETE", "/credentials", None),+ ("POST", "/sms-configs", {"mode": "manual"}),+ ("DELETE", "/sms-configs/smsc_test", None),+ ("POST", "/sms-configs/smsc_test/phone-numbers", {"phone_number": "+14155550123"}),+ ],+)+def test_lifecycle_lock_timeout_returns_conflict_on_every_mutation(+ twilio_client: TestClient, monkeypatch: pytest.MonkeyPatch, method: str, path: str, payload: dict | None+) -> None:+ from skyvern.forge.sdk.db.repositories.sms import SMSLifecycleLockTimeout++ database = _database(token=_credential_token())+ database.sms.get_phone_number.return_value = _registered_phone(_config())+ database.sms.get_sms_config.return_value = _config(mode="manual")+ provider, _ = _patch_client(monkeypatch)+ provider.get_incoming_phone_number.return_value = _provider_number()++ @asynccontextmanager+ async def timed_out(*args):+ raise SMSLifecycleLockTimeout("busy")+ yield++ database.sms.lifecycle_lock.side_effect = timed_out+ database.sms.organization_lock.side_effect = timed_out+ monkeypatch.setattr(twilio_integration.app, "DATABASE", database)+ response = twilio_client.request(method, f"/twilio{path}", json=payload)+ assert response.status_code == 409+ assert response.json()["detail"] == "SMS number operation is busy. Try again."+ provider.update_inbound_sms_config.assert_not_awaited()diff --git a/tests/unit/webeye/test_browser_session_response.py b/tests/unit/webeye/test_browser_session_response.pyindex 1c33f08ba..8022916f8 100644--- a/tests/unit/webeye/test_browser_session_response.py+++ b/tests/unit/webeye/test_browser_session_response.py@@ -38,6 +38,7 @@ PINNED_CLIENT_FIELDS = frozenset("created_at","modified_at","deleted_at",+ "created_by","warning",})@@ -61,6 +62,7 @@ CLIENT_VISIBLE_ROW_FIELDS = frozenset("created_at","modified_at","deleted_at",+ "created_by",})diff --git a/tests/unit/workflow/test_web_search_block.py b/tests/unit/workflow/test_web_search_block.pyindex 70ba528a0..54917d404 100644--- a/tests/unit/workflow/test_web_search_block.py+++ b/tests/unit/workflow/test_web_search_block.py@@ -3,6 +3,7 @@ from copy import deepcopyfrom datetime import UTC, datetimefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock+from urllib.parse import parse_qs, urlsplitimport pytestfrom jsonschema import Draft202012Validator@@ -260,6 +261,36 @@ async def test_search_completes_with_validated_partial_results(handler.assert_awaited()+async def test_google_site_filter_refetches_off_site_page_at_most_twice(+ search_setup: tuple[WebSearchBlock, WorkflowRunContext, AsyncMock],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ original, _, _ = search_setup+ block = original.model_copy(update={"provider": "google", "query": "site:example.com documents", "prompt": None})+ off_site_page = {+ "search_metadata": {"status": "Success"},+ "organic_results": [{"link": "https://unrelated.test/a"}, {"link": "https://unrelated.test/b"}],+ "serpapi_pagination": {"next": "https://serpapi.com/search.json?start=10"},+ }+ request = AsyncMock(side_effect=[off_site_page] * 3)+ monkeypatch.setattr(search_module.settings, "SERPAPI_API_KEY", "test-google-key")+ monkeypatch.setattr(WebSearchBlock, "_request", request)++ result = await block.execute("workflow-run-test", "block-run-test", "org-test")++ assert result.success is True+ assert result.status == BlockStatus.completed+ output = result.output_parameter_value+ assert output["results"] == []+ assert request.await_count == 3+ assert all(call.args[0] == "google" for call in request.await_args_list)+ parameters = [parse_qs(urlsplit(call.args[1]).query) for call in request.await_args_list]+ assert "no_cache" not in parameters[0]+ assert parameters[1] == parameters[2] == {**parameters[0], "no_cache": ["true"]}+ assert all(params["start"] == ["0"] for params in parameters)++@pytest.mark.asyncio@pytest.mark.parametrize("provider", ["google", "auto"])async def test_search_first_page_timeout_preserves_fallback(