Skip to content

Automate browser based workflows with AI

Support blank browser profile creation (#6835)

Suchintan15a24f024703
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 7662d4ef9..18d998fe9 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -2543,7 +2543,7 @@
"Browser Profiles"
],
"summary": "Create a browser profile",
- "description": "Create a browser profile from a persistent browser session or workflow run.",
+ "description": "Create a blank browser profile, or create one from a persistent browser session or workflow run.",
"operationId": "create_browser_profile_v1_browser_profiles_post",
"parameters": [
{
@@ -2587,7 +2587,7 @@
}
},
"400": {
- "description": "Invalid request - missing source or source not found"
+ "description": "Invalid request - source not found or source archive unavailable"
},
"409": {
"description": "Browser profile name already exists"
@@ -2609,11 +2609,11 @@
"code-samples": [
{
"sdk": "python",
- "code": "from skyvern import Skyvern\n\nskyvern = Skyvern(api_key=\"YOUR_API_KEY\")\n# Create a browser profile from a persistent browser session\nbrowser_profile = await skyvern.browser_profiles.create_browser_profile(\n name=\"My Profile\",\n browser_session_id=\"pbs_123\",\n)\nprint(browser_profile)\n\n# Or create from a workflow run with persist_browser_session=True\nbrowser_profile = await skyvern.browser_profiles.create_browser_profile(\n name=\"My Profile\",\n workflow_run_id=\"wr_123\",\n)\nprint(browser_profile)\n"
+ "code": "from skyvern import Skyvern\n\nskyvern = Skyvern(api_key=\"YOUR_API_KEY\")\n# Create a blank browser profile for future runs\nblank_profile = await skyvern.browser_profiles.create_browser_profile(\n name=\"Fresh Profile\",\n)\nprint(blank_profile)\n\n# Create a browser profile from a persistent browser session\nbrowser_profile = await skyvern.browser_profiles.create_browser_profile(\n name=\"My Profile\",\n browser_session_id=\"pbs_123\",\n)\nprint(browser_profile)\n\n# Or create from a workflow run with persist_browser_session=True\nbrowser_profile = await skyvern.browser_profiles.create_browser_profile(\n name=\"My Profile\",\n workflow_run_id=\"wr_123\",\n)\nprint(browser_profile)\n"
},
{
"sdk": "typescript",
- "code": "import { SkyvernClient } from \"@skyvern/client\";\n\nconst skyvern = new SkyvernClient({ apiKey: \"YOUR_API_KEY\" });\n// Create a browser profile from a persistent browser session\nconst browserProfile = await skyvern.browserProfiles.createBrowserProfile({\n name: \"My Profile\",\n browser_session_id: \"pbs_123\",\n});\nconsole.log(browserProfile);\n\n// Or create from a workflow run with persist_browser_session=True\nconst browserProfile2 = await skyvern.browserProfiles.createBrowserProfile({\n name: \"My Profile\",\n workflow_run_id: \"wr_123\",\n});\nconsole.log(browserProfile2);\n"
+ "code": "import { SkyvernClient } from \"@skyvern/client\";\n\nconst skyvern = new SkyvernClient({ apiKey: \"YOUR_API_KEY\" });\n// Create a blank browser profile for future runs\nconst blankProfile = await skyvern.browserProfiles.createBrowserProfile({\n name: \"Fresh Profile\",\n});\nconsole.log(blankProfile);\n\n// Create a browser profile from a persistent browser session\nconst browserProfile = await skyvern.browserProfiles.createBrowserProfile({\n name: \"My Profile\",\n browser_session_id: \"pbs_123\",\n});\nconsole.log(browserProfile);\n\n// Or create from a workflow run with persist_browser_session=True\nconst browserProfile2 = await skyvern.browserProfiles.createBrowserProfile({\n name: \"My Profile\",\n workflow_run_id: \"wr_123\",\n});\nconsole.log(browserProfile2);\n"
}
]
}
@@ -9731,26 +9731,28 @@
"browser_session_id": {
"anyOf": [
{
- "type": "string"
+ "type": "string",
+ "minLength": 1
},
{
"type": "null"
}
],
"title": "Browser Session Id",
- "description": "Persistent browser session to convert into a profile"
+ "description": "Persistent browser session to convert into a profile. Omit for a blank profile."
},
"workflow_run_id": {
"anyOf": [
{
- "type": "string"
+ "type": "string",
+ "minLength": 1
},
{
"type": "null"
}
],
"title": "Workflow Run Id",
- "description": "Workflow run whose persisted session should be captured"
+ "description": "Workflow run whose persisted session should be captured. Omit for a blank profile."
}
},
"type": "object",
diff --git a/docs/developers/optimization/browser-profiles.mdx b/docs/developers/optimization/browser-profiles.mdx
index d30d7feb1..873d7f7d6 100644
--- a/docs/developers/optimization/browser-profiles.mdx
+++ b/docs/developers/optimization/browser-profiles.mdx
@@ -24,6 +24,8 @@ Profiles are ideal when you:
## How profiles work
+You can create a blank profile with only `name` and optional `description`, then pass that profile to future agent runs. Blank profiles are seeded from the configured default browser profile directory when available, with a minimal loadable profile skeleton as a fallback.
+
When an agent runs with `persist_browser_session=true`, Skyvern archives the browser state (cookies, storage, session files) after the run completes. This archiving happens asynchronously in the background. Once the archive is ready, you can create a profile from it, then pass that profile to future agent runs to restore the saved state.
For [browser sessions](/developers/optimization/browser-sessions), profile saving is opt-in: a session archives its state when it ends only if it has `generate_browser_profile` enabled or was started from a saved profile. See [Save a session's profile](/developers/optimization/browser-sessions#save-a-sessions-profile).
@@ -32,14 +34,72 @@ For [browser sessions](/developers/optimization/browser-sessions), profile savin
## Create a Browser Profile
+Create a blank profile when you want a reusable profile ID before any browsing has happened. Create a sourced profile when you want to capture cookies, localStorage, and session files from a workflow run or browser session.
+
+### Blank profile
+
+<CodeGroup>
+```python Python
+import asyncio
+from skyvern import Skyvern
+
+async def main():
+ client = Skyvern(api_key="YOUR_API_KEY")
+
+ profile = await client.create_browser_profile(
+ name="fresh-profile",
+ description="Blank profile for future runs",
+ )
+ print(f"Profile created: {profile.browser_profile_id}")
+
+asyncio.run(main())
+```
+
+```typescript TypeScript
+import { Skyvern } from "@skyvern/client";
+
+async function main() {
+ const client = new Skyvern({ apiKey: process.env.SKYVERN_API_KEY! });
+
+ const profile = await client.createBrowserProfile({
+ name: "fresh-profile",
+ description: "Blank profile for future runs",
+ });
+
+ console.log(`Profile created: ${profile.browser_profile_id}`);
+}
+
+main();
+```
+
+```bash cURL
+curl -s -X POST "https://api.skyvern.com/v1/browser_profiles" \
+ -H "x-api-key: $SKYVERN_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "name": "fresh-profile",
+ "description": "Blank profile for future runs"
+ }'
+```
+</CodeGroup>
+
+**Parameters:**
+
+| Parameter | Type | Description |
+|----------------------|--------|---------------------------------------|
+| `name` | string | Required unique display name |
+| `description` | string | Optional profile description |
+| `browser_session_id` | string | Omit for a blank profile |
+| `workflow_run_id` | string | Omit for a blank profile |
+
+### From an agent run
+
Create an agent with `persist_browser_session=true` in the agent definition, run it, wait for completion, then create a profile from the run. Session archiving happens asynchronously, so add brief retry logic when creating the profile.
<Note>
`persist_browser_session` must be set when **creating the agent**, not when running it. It is an agent definition property, not a runtime parameter.
</Note>
-### From an agent run
-
<CodeGroup>
```python Python
import asyncio
diff --git a/fern/browser-sessions/browser-profiles.mdx b/fern/browser-sessions/browser-profiles.mdx
index a19c6d80f..1581bca94 100644
--- a/fern/browser-sessions/browser-profiles.mdx
+++ b/fern/browser-sessions/browser-profiles.mdx
@@ -12,16 +12,32 @@ Browser Profiles capture the full browser state (cookies, storage, session files
- Want to fan out multiple workflows that all reuse the same authenticated browser state.
- Need an audit-friendly way to persist state separate from long-lived browser sessions.
-Whereas a **browser session** is a temporary, real-time browser, a **browser profile** is a reusable snapshot created from that session (or from a workflow run that persisted its session). Profiles are scoped to your organization and can be reused as often as you need.
+Whereas a **browser session** is a temporary, real-time browser, a **browser profile** is a reusable profile archive. You can create one blank, from a browser session, or from a workflow run that persisted its session. Profiles are scoped to your organization and can be reused as often as you need.
## How Browser Profiles Work
-1. Run a workflow with `persist_browser_session: true` **or** open a persistent browser session.
-2. Close the workflow run or browser session so Skyvern can upload the archived state.
+1. Create a blank profile with only `name`, or run a workflow with `persist_browser_session: true` **or** open a persistent browser session.
+2. For workflow and browser-session sources, close the workflow run or browser session so Skyvern can upload the archived state.
3. Create a browser profile from that source once the upload finishes.
-4. Pass `browser_profile_id` to subsequent workflow runs to restore the saved state instantly.
+4. Pass `browser_profile_id` to subsequent workflow runs to start from the saved profile archive.
-## Option A — Create a Profile from a Workflow Run
+## Option A — Create a Blank Profile
+
+Use this approach when you want a reusable profile ID before any browsing has happened. Skyvern seeds the profile from the configured default browser profile directory when available, with a minimal loadable profile skeleton as a fallback.
+
+```python
+from skyvern import Skyvern
+
+skyvern = Skyvern(api_key="YOUR_API_KEY")
+
+browser_profile = await skyvern.browser_profiles.create_browser_profile(
+ name="fresh-profile",
+ description="Blank profile for future runs",
+)
+print(browser_profile.browser_profile_id)
+```
+
+## Option B — Create a Profile from a Workflow Run
Use this approach when you already ran a workflow with `persist_browser_session: true`. Always poll the run (e.g., `GET /v1/runs/{run_id}`) until it reaches `status = "completed"` before attempting to create the profile—Skyvern only begins uploading the archived browser state once the run finishes.
@@ -67,7 +83,7 @@ async def create_profile_with_retry(
raise RuntimeError("Session never finished uploading a profile archive")
```
-## Option B — Create a Profile from a Browser Session
+## Option C — Create a Profile from a Browser Session
If you opened a persistent browser session directly (without a workflow), close it and then create a profile using the session ID:
@@ -100,4 +116,3 @@ print(workflow_run.run_id)
```
If the workflow also sets `persist_browser_session: true`, you can capture a fresh profile again at the end and keep the cycle going.
-
diff --git a/fern/openapi/skyvern_openapi.json b/fern/openapi/skyvern_openapi.json
index d841bd60a..8fbe6f882 100644
--- a/fern/openapi/skyvern_openapi.json
+++ b/fern/openapi/skyvern_openapi.json
@@ -2241,7 +2241,7 @@
"Browser Profiles"
],
"summary": "Create a browser profile",
- "description": "Create a browser profile from a persistent browser session or workflow run.",
+ "description": "Create a blank browser profile, or create one from a persistent browser session or workflow run.",
"operationId": "create_browser_profile_v1_browser_profiles_post",
"parameters": [
{
@@ -2285,7 +2285,7 @@
}
},
"400": {
- "description": "Invalid request - missing source or source not found"
+ "description": "Invalid request - source not found or source archive unavailable"
},
"409": {
"description": "Browser profile name already exists"
@@ -2307,11 +2307,11 @@
"code-samples": [
{
"sdk": "python",
- "code": "from skyvern import Skyvern\n\nskyvern = Skyvern(api_key=\"YOUR_API_KEY\")\n# Create a browser profile from a persistent browser session\nbrowser_profile = await skyvern.browser_profiles.create_browser_profile(\n name=\"My Profile\",\n browser_session_id=\"pbs_123\",\n)\nprint(browser_profile)\n\n# Or create from a workflow run with persist_browser_session=True\nbrowser_profile = await skyvern.browser_profiles.create_browser_profile(\n name=\"My Profile\",\n workflow_run_id=\"wr_123\",\n)\nprint(browser_profile)\n"
+ "code": "from skyvern import Skyvern\n\nskyvern = Skyvern(api_key=\"YOUR_API_KEY\")\n# Create a blank browser profile for future runs\nblank_profile = await skyvern.browser_profiles.create_browser_profile(\n name=\"Fresh Profile\",\n)\nprint(blank_profile)\n\n# Create a browser profile from a persistent browser session\nbrowser_profile = await skyvern.browser_profiles.create_browser_profile(\n name=\"My Profile\",\n browser_session_id=\"pbs_123\",\n)\nprint(browser_profile)\n\n# Or create from a workflow run with persist_browser_session=True\nbrowser_profile = await skyvern.browser_profiles.create_browser_profile(\n name=\"My Profile\",\n workflow_run_id=\"wr_123\",\n)\nprint(browser_profile)\n"
},
{
"sdk": "typescript",
- "code": "import { SkyvernClient } from \"@skyvern/client\";\n\nconst skyvern = new SkyvernClient({ apiKey: \"YOUR_API_KEY\" });\n// Create a browser profile from a persistent browser session\nconst browserProfile = await skyvern.browserProfiles.createBrowserProfile({\n name: \"My Profile\",\n browser_session_id: \"pbs_123\",\n});\nconsole.log(browserProfile);\n\n// Or create from a workflow run with persist_browser_session=True\nconst browserProfile2 = await skyvern.browserProfiles.createBrowserProfile({\n name: \"My Profile\",\n workflow_run_id: \"wr_123\",\n});\nconsole.log(browserProfile2);\n"
+ "code": "import { SkyvernClient } from \"@skyvern/client\";\n\nconst skyvern = new SkyvernClient({ apiKey: \"YOUR_API_KEY\" });\n// Create a blank browser profile for future runs\nconst blankProfile = await skyvern.browserProfiles.createBrowserProfile({\n name: \"Fresh Profile\",\n});\nconsole.log(blankProfile);\n\n// Create a browser profile from a persistent browser session\nconst browserProfile = await skyvern.browserProfiles.createBrowserProfile({\n name: \"My Profile\",\n browser_session_id: \"pbs_123\",\n});\nconsole.log(browserProfile);\n\n// Or create from a workflow run with persist_browser_session=True\nconst browserProfile2 = await skyvern.browserProfiles.createBrowserProfile({\n name: \"My Profile\",\n workflow_run_id: \"wr_123\",\n});\nconsole.log(browserProfile2);\n"
}
]
}
@@ -9233,26 +9233,28 @@
"browser_session_id": {
"anyOf": [
{
- "type": "string"
+ "type": "string",
+ "minLength": 1
},
{
"type": "null"
}
],
"title": "Browser Session Id",
- "description": "Persistent browser session to convert into a profile"
+ "description": "Persistent browser session to convert into a profile. Omit for a blank profile."
},
"workflow_run_id": {
"anyOf": [
{
- "type": "string"
+ "type": "string",
+ "minLength": 1
},
{
"type": "null"
}
],
"title": "Workflow Run Id",
- "description": "Workflow run whose persisted session should be captured"
+ "description": "Workflow run whose persisted session should be captured. Omit for a blank profile."
}
},
"type": "object",
diff --git a/skyvern/client/client.py b/skyvern/client/client.py
index 5d4a5c698..e895338ae 100644
--- a/skyvern/client/client.py
+++ b/skyvern/client/client.py
@@ -1623,7 +1623,7 @@ class Skyvern:
request_options: typing.Optional[RequestOptions] = None,
) -> BrowserProfile:
"""
- Create a browser profile from a persistent browser session or workflow run.
+ Create a blank browser profile, or create one from a persistent browser session or workflow run.
Parameters
----------
@@ -1634,10 +1634,10 @@ class Skyvern:
Optional profile description
browser_session_id : typing.Optional[str]
- Persistent browser session to convert into a profile
+ Persistent browser session to convert into a profile. Omit for a blank profile.
workflow_run_id : typing.Optional[str]
- Workflow run whose persisted session should be captured
+ Workflow run whose persisted session should be captured. Omit for a blank profile.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -4571,7 +4571,7 @@ class AsyncSkyvern:
request_options: typing.Optional[RequestOptions] = None,
) -> BrowserProfile:
"""
- Create a browser profile from a persistent browser session or workflow run.
+ Create a blank browser profile, or create one from a persistent browser session or workflow run.
Parameters
----------
@@ -4582,10 +4582,10 @@ class AsyncSkyvern:
Optional profile description
browser_session_id : typing.Optional[str]
- Persistent browser session to convert into a profile
+ Persistent browser session to convert into a profile. Omit for a blank profile.
workflow_run_id : typing.Optional[str]
- Workflow run whose persisted session should be captured
+ Workflow run whose persisted session should be captured. Omit for a blank profile.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
diff --git a/skyvern/client/raw_client.py b/skyvern/client/raw_client.py
index 8fdfd6508..1b7aed09c 100644
--- a/skyvern/client/raw_client.py
+++ b/skyvern/client/raw_client.py
@@ -2184,7 +2184,7 @@ class RawSkyvern:
request_options: typing.Optional[RequestOptions] = None,
) -> HttpResponse[BrowserProfile]:
"""
- Create a browser profile from a persistent browser session or workflow run.
+ Create a blank browser profile, or create one from a persistent browser session or workflow run.
Parameters
----------
@@ -2195,10 +2195,10 @@ class RawSkyvern:
Optional profile description
browser_session_id : typing.Optional[str]
- Persistent browser session to convert into a profile
+ Persistent browser session to convert into a profile. Omit for a blank profile.
workflow_run_id : typing.Optional[str]
- Workflow run whose persisted session should be captured
+ Workflow run whose persisted session should be captured. Omit for a blank profile.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -5976,7 +5976,7 @@ class AsyncRawSkyvern:
request_options: typing.Optional[RequestOptions] = None,
) -> AsyncHttpResponse[BrowserProfile]:
"""
- Create a browser profile from a persistent browser session or workflow run.
+ Create a blank browser profile, or create one from a persistent browser session or workflow run.
Parameters
----------
@@ -5987,10 +5987,10 @@ class AsyncRawSkyvern:
Optional profile description
browser_session_id : typing.Optional[str]
- Persistent browser session to convert into a profile
+ Persistent browser session to convert into a profile. Omit for a blank profile.
workflow_run_id : typing.Optional[str]
- Workflow run whose persisted session should be captured
+ Workflow run whose persisted session should be captured. Omit for a blank profile.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
diff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.py
index d623d82d3..f19aa1109 100644
--- a/skyvern/forge/sdk/db/agent_db.py
+++ b/skyvern/forge/sdk/db/agent_db.py
@@ -746,6 +746,9 @@ class AgentDB(BaseAlchemyDB):
async def delete_browser_profile(self, *args: Any, **kwargs: Any) -> Any:
return await self.browser_sessions.delete_browser_profile(*args, **kwargs)
+ async def hard_delete_browser_profile(self, *args: Any, **kwargs: Any) -> Any:
+ return await self.browser_sessions.hard_delete_browser_profile(*args, **kwargs)
+
async def get_active_persistent_browser_sessions(self, *args: Any, **kwargs: Any) -> Any:
return await self.browser_sessions.get_active_persistent_browser_sessions(*args, **kwargs)
diff --git a/skyvern/forge/sdk/db/repositories/browser_sessions.py b/skyvern/forge/sdk/db/repositories/browser_sessions.py
index c21d0a21e..4cf0b77b5 100644
--- a/skyvern/forge/sdk/db/repositories/browser_sessions.py
+++ b/skyvern/forge/sdk/db/repositories/browser_sessions.py
@@ -126,6 +126,24 @@ class BrowserSessionsRepository(BaseRepository):
browser_profile.deleted_at = naive_utc_now()
await session.commit()
+ @db_operation("hard_delete_browser_profile")
+ async def hard_delete_browser_profile(
+ self,
+ profile_id: str,
+ organization_id: str,
+ ) -> None:
+ async with self.Session() as session:
+ query = (
+ select(BrowserProfileModel)
+ .filter_by(browser_profile_id=profile_id)
+ .filter_by(organization_id=organization_id)
+ )
+ browser_profile = (await session.scalars(query)).first()
+ if not browser_profile:
+ raise BrowserProfileNotFound(profile_id=profile_id, organization_id=organization_id)
+ await session.delete(browser_profile)
+ await session.commit()
+
@db_operation("update_browser_profile")
async def update_browser_profile(
self,
diff --git a/skyvern/forge/sdk/routes/browser_profiles.py b/skyvern/forge/sdk/routes/browser_profiles.py
index 6c06cda79..38e0ac1db 100644
--- a/skyvern/forge/sdk/routes/browser_profiles.py
+++ b/skyvern/forge/sdk/routes/browser_profiles.py
@@ -1,10 +1,13 @@
import asyncio
+import shutil
+from pathlib import Path as FilePath
from typing import NoReturn
import structlog
from fastapi import Depends, HTTPException, Path, Query, status
from sqlalchemy.exc import IntegrityError
+from skyvern.config import settings
from skyvern.exceptions import (
BrowserProfileNotFound,
BrowserSessionNotFound,
@@ -12,6 +15,7 @@ from skyvern.exceptions import (
WorkflowRunNotFound,
)
from skyvern.forge import app
+from skyvern.forge.sdk.api.files import make_temp_directory
from skyvern.forge.sdk.routes.code_samples import (
CREATE_BROWSER_PROFILE_CODE_SAMPLE_PYTHON,
CREATE_BROWSER_PROFILE_CODE_SAMPLE_TS,
@@ -36,6 +40,27 @@ from skyvern.forge.sdk.services import org_auth_service
LOG = structlog.get_logger()
+DEFAULT_PROFILE_BROWSER_TYPES = ("chrome", "chromium")
+DEFAULT_PROFILE_COPY_IGNORE = {
+ "Snapshots",
+ "GrShaderCache",
+ "ShaderCache",
+ "GraphiteDawnCache",
+ "DawnCache",
+ "DawnGraphiteCache",
+ "DawnWebGPUCache",
+ "Guest Profile",
+ "Profile 2",
+ "Profile 3",
+ "BrowserMetrics",
+ "Crashpad",
+ "CrashpadMetrics-active.pma",
+ "SingletonCookie",
+ "SingletonLock",
+ "SingletonSocket",
+ "DevToolsActivePort",
+}
+
def _handle_duplicate_profile_name(*, organization_id: str, name: str, exc: IntegrityError) -> NoReturn:
LOG.warning(
@@ -55,7 +80,7 @@ def _handle_duplicate_profile_name(*, organization_id: str, name: str, exc: Inte
response_model=BrowserProfile,
tags=["Browser Profiles"],
summary="Create a browser profile",
- description="Create a browser profile from a persistent browser session or workflow run.",
+ description=("Create a blank browser profile, or create one from a persistent browser session or workflow run."),
openapi_extra={
"x-fern-sdk-method-name": "create_browser_profile",
"x-fern-examples": [
@@ -69,7 +94,7 @@ def _handle_duplicate_profile_name(*, organization_id: str, name: str, exc: Inte
},
responses={
200: {"description": "Successfully created browser profile"},
- 400: {"description": "Invalid request - missing source or source not found"},
+ 400: {"description": "Invalid request - source not found or source archive unavailable"},
409: {"description": "Browser profile name already exists"},
},
)
@@ -90,7 +115,7 @@ async def create_browser_profile(
workflow_run_id=request.workflow_run_id,
)
- if request.browser_session_id:
+ if request.browser_session_id is not None:
browser_session_id = request.browser_session_id
return await _create_profile_from_session(
organization_id=organization_id,
@@ -99,13 +124,19 @@ async def create_browser_profile(
browser_session_id=browser_session_id,
)
- workflow_run_id = request.workflow_run_id
- assert workflow_run_id is not None # model validator guarantees one of the sources
- return await _create_profile_from_workflow_run(
+ if request.workflow_run_id is not None:
+ return await _create_profile_from_workflow_run(
+ organization_id=organization_id,
+ name=request.name,
+ description=request.description,
+ workflow_run_id=request.workflow_run_id,
+ )
+
+ await app.RATE_LIMITER.rate_limit_submit_run(organization_id)
+ return await _create_empty_profile(
organization_id=organization_id,
name=request.name,
description=request.description,
- workflow_run_id=workflow_run_id,
)
@@ -393,6 +424,172 @@ async def delete_browser_profile(
)
+def _create_empty_browser_profile_directory() -> str:
+ profile_dir = FilePath(make_temp_directory(prefix="skyvern_empty_browser_profile_"))
+ _seed_empty_browser_profile_directory(profile_dir)
+ return str(profile_dir)
+
+
+def _default_browser_profile_template_candidates() -> list[FilePath]:
+ if not settings.DEFAULT_BROWSER_PROFILE_DIR:
+ return []
+
+ base_dir = FilePath(settings.DEFAULT_BROWSER_PROFILE_DIR)
+ candidates = [base_dir]
+ for browser_type in DEFAULT_PROFILE_BROWSER_TYPES:
+ candidates.extend(_versioned_browser_profile_template_candidates(base_dir, browser_type))
+ candidates.append(base_dir / browser_type)
+ return candidates
+
+
+def _versioned_browser_profile_template_candidates(base_dir: FilePath, browser_type: str) -> list[FilePath]:
+ prefix = f"{browser_type}_"
+ candidates: list[tuple[int, FilePath]] = []
+ try:
+ children = list(base_dir.iterdir())
+ except OSError:
+ return []
+
+ for child in children:
+ if not child.is_dir() or not child.name.startswith(prefix):
+ continue
+ suffix = child.name.removeprefix(prefix)
+ if not suffix.isdigit():
+ continue
+ candidates.append((int(suffix), child))
+
+ candidates.sort(key=lambda candidate: candidate[0], reverse=True)
+ return [path for _, path in candidates]
+
+
+def _is_valid_browser_profile_template(directory: FilePath) -> bool:
+ return (
+ directory.is_dir()
+ and (directory / "Default").is_dir()
+ and (directory / "Default" / "Preferences").is_file()
+ and (directory / "Local State").is_file()
+ )
+
+
+def _clear_directory(directory: FilePath) -> None:
+ for child in directory.iterdir():
+ if child.is_dir():
+ shutil.rmtree(child, ignore_errors=True)
+ else:
+ child.unlink(missing_ok=True)
+
+
+def _copy_browser_profile_template(source_dir: FilePath, destination_dir: FilePath) -> None:
+ for source_child in source_dir.iterdir():
+ if source_child.name in DEFAULT_PROFILE_COPY_IGNORE:
+ continue
+
+ destination_child = destination_dir / source_child.name
+ if source_child.is_dir():
+ shutil.copytree(source_child, destination_child)
+ else:
+ shutil.copy2(source_child, destination_child)
+
+
+def _seed_minimal_empty_browser_profile_directory(profile_dir: FilePath) -> None:
+ default_dir = profile_dir / "Default"
+ default_dir.mkdir(parents=True, exist_ok=True)
+ (default_dir / "Preferences").write_text("{}", encoding="utf-8")
+ (profile_dir / "Local State").write_text("{}", encoding="utf-8")
+
+
+def _seed_empty_browser_profile_directory(profile_dir: FilePath) -> None:
+ for template_dir in _default_browser_profile_template_candidates():
+ if not _is_valid_browser_profile_template(template_dir):
+ continue
+ try:
+ _copy_browser_profile_template(template_dir, profile_dir)
+ LOG.info(
+ "Seeded empty browser profile from default profile template",
+ template_dir=str(template_dir),
+ profile_dir=str(profile_dir),
+ )
+ return
+ except Exception:
+ LOG.warning(
+ "Failed to seed empty browser profile from default template, falling back",
+ template_dir=str(template_dir),
+ profile_dir=str(profile_dir),
+ exc_info=True,
+ )
+ _clear_directory(profile_dir)
+
+ _seed_minimal_empty_browser_profile_directory(profile_dir)
+ LOG.info("Seeded empty browser profile from minimal profile skeleton", profile_dir=str(profile_dir))
+
+
+async def _hard_delete_created_profile_after_store_failure(
+ *,
+ organization_id: str,
+ browser_profile_id: str,
+) -> bool:
+ try:
+ await app.DATABASE.browser_sessions.hard_delete_browser_profile(
+ browser_profile_id, organization_id=organization_id
+ )
+ except Exception:
+ LOG.exception(
+ "Failed to roll back browser profile after storage failure",
+ organization_id=organization_id,
+ browser_profile_id=browser_profile_id,
+ )
+ return False
+ return True
+
+
+async def _create_empty_profile(
+ *,
+ organization_id: str,
+ name: str,
+ description: str | None,
+) -> BrowserProfile:
+ # Seed before inserting so local setup failures never reserve a profile name.
+ profile_dir = _create_empty_browser_profile_directory()
+ try:
+ try:
+ profile = await app.DATABASE.browser_sessions.create_browser_profile(
+ organization_id=organization_id,
+ name=name,
+ description=description,
+ )
+ except IntegrityError as exc:
+ _handle_duplicate_profile_name(organization_id=organization_id, name=name, exc=exc)
+
+ try:
+ await app.STORAGE.store_browser_profile(
+ organization_id=organization_id,
+ profile_id=profile.browser_profile_id,
+ directory=profile_dir,
+ )
+ except Exception:
+ rolled_back = await _hard_delete_created_profile_after_store_failure(
+ organization_id=organization_id,
+ browser_profile_id=profile.browser_profile_id,
+ )
+ LOG.error(
+ "Failed to store empty browser profile artifacts",
+ organization_id=organization_id,
+ browser_profile_id=profile.browser_profile_id,
+ rolled_back=rolled_back,
+ exc_info=True,
+ )
+ raise
+ finally:
+ shutil.rmtree(profile_dir, ignore_errors=True)
+
+ LOG.info(
+ "Created empty browser profile",
+ organization_id=organization_id,
+ browser_profile_id=profile.browser_profile_id,
+ )
+ return profile
+
+
async def _create_profile_from_session(
*,
organization_id: str,
@@ -490,14 +687,15 @@ async def _create_profile_from_session(
directory=session_dir,
)
except Exception:
- # Rollback: delete the profile if storage fails
- await app.DATABASE.browser_sessions.delete_browser_profile(
- profile.browser_profile_id, organization_id=organization_id
+ rolled_back = await _hard_delete_created_profile_after_store_failure(
+ organization_id=organization_id,
+ browser_profile_id=profile.browser_profile_id,
)
LOG.error(
- "Failed to store browser profile artifacts, rolled back profile creation",
+ "Failed to store browser profile artifacts",
organization_id=organization_id,
browser_profile_id=profile.browser_profile_id,
+ rolled_back=rolled_back,
exc_info=True,
)
raise
@@ -621,15 +819,16 @@ async def _create_profile_from_workflow_run(
workflow_run_id=workflow_run_id,
)
except Exception:
- # Rollback: delete the profile if storage fails
- await app.DATABASE.browser_sessions.delete_browser_profile(
- profile.browser_profile_id, organization_id=organization_id
+ rolled_back = await _hard_delete_created_profile_after_store_failure(
+ organization_id=organization_id,
+ browser_profile_id=profile.browser_profile_id,
)
LOG.error(
- "Failed to store browser profile artifacts, rolled back profile creation",
+ "Failed to store browser profile artifacts",
organization_id=organization_id,
browser_profile_id=profile.browser_profile_id,
workflow_run_id=workflow_run_id,
+ rolled_back=rolled_back,
exc_info=True,
)
raise
diff --git a/skyvern/forge/sdk/routes/code_samples.py b/skyvern/forge/sdk/routes/code_samples.py
index 7d4b61655..18e9c6607 100644
--- a/skyvern/forge/sdk/routes/code_samples.py
+++ b/skyvern/forge/sdk/routes/code_samples.py
@@ -907,6 +907,12 @@ console.log(browserSessions);
CREATE_BROWSER_PROFILE_CODE_SAMPLE_PYTHON = """from skyvern import Skyvern
skyvern = Skyvern(api_key="YOUR_API_KEY")
+# Create a blank browser profile for future runs
+blank_profile = await skyvern.browser_profiles.create_browser_profile(
+ name="Fresh Profile",
+)
+print(blank_profile)
+
# Create a browser profile from a persistent browser session
browser_profile = await skyvern.browser_profiles.create_browser_profile(
name="My Profile",
@@ -924,6 +930,12 @@ print(browser_profile)
CREATE_BROWSER_PROFILE_CODE_SAMPLE_TS = """import { SkyvernClient } from "@skyvern/client";
const skyvern = new SkyvernClient({ apiKey: "YOUR_API_KEY" });
+// Create a blank browser profile for future runs
+const blankProfile = await skyvern.browserProfiles.createBrowserProfile({
+ name: "Fresh Profile",
+});
+console.log(blankProfile);
+
// Create a browser profile from a persistent browser session
const browserProfile = await skyvern.browserProfiles.createBrowserProfile({
name: "My Profile",
diff --git a/skyvern/forge/sdk/schemas/browser_profiles.py b/skyvern/forge/sdk/schemas/browser_profiles.py
index b55c9fe97..2c259de5c 100644
--- a/skyvern/forge/sdk/schemas/browser_profiles.py
+++ b/skyvern/forge/sdk/schemas/browser_profiles.py
@@ -22,16 +22,20 @@ class CreateBrowserProfileRequest(BaseModel):
name: str = Field(..., min_length=1, description="Name for the browser profile")
description: str | None = Field(None, description="Optional profile description")
browser_session_id: str | None = Field(
- default=None, description="Persistent browser session to convert into a profile"
+ default=None,
+ min_length=1,
+ description="Persistent browser session to convert into a profile. Omit for a blank profile.",
)
workflow_run_id: str | None = Field(
- default=None, description="Workflow run whose persisted session should be captured"
+ default=None,
+ min_length=1,
+ description="Workflow run whose persisted session should be captured. Omit for a blank profile.",
)
@model_validator(mode="after")
def _validate_source(self) -> "CreateBrowserProfileRequest":
- if bool(self.browser_session_id) == bool(self.workflow_run_id):
- raise ValueError("Provide either browser_session_id or workflow_run_id")
+ if self.browser_session_id is not None and self.workflow_run_id is not None:
+ raise ValueError("Provide only one of browser_session_id or workflow_run_id")
return self
diff --git a/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py b/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
index 44ad73faa..52441d61f 100644
--- a/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
+++ b/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
@@ -2,22 +2,28 @@
from __future__ import annotations
+from collections.abc import Iterator
from datetime import datetime
+from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
import pytest
-from fastapi import FastAPI, Request
+from fastapi import APIRouter, FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
+from pydantic import ValidationError
+from sqlalchemy.exc import IntegrityError
from skyvern.exceptions import SkyvernHTTPException
from skyvern.forge import app as forge_app
-from skyvern.forge.sdk.routes import routers as routers_module
-from skyvern.forge.sdk.schemas.browser_profiles import BrowserProfile
+from skyvern.forge.sdk.routes import browser_profiles as browser_profiles_route
+from skyvern.forge.sdk.schemas.browser_profiles import BrowserProfile, CreateBrowserProfileRequest
from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession
from skyvern.forge.sdk.services import org_auth_service
+_default_profile_template_candidates = browser_profiles_route._default_browser_profile_template_candidates
+
def _session(**kwargs: object) -> PersistentBrowserSession:
base: dict[str, object] = {
@@ -40,28 +46,84 @@ def _profile() -> BrowserProfile:
)
-def _build_client(monkeypatch: pytest.MonkeyPatch) -> tuple[TestClient, SimpleNamespace]:
[email protected](autouse=True)
+def _restore_forge_app() -> Iterator[None]:
+ previous_app = object.__getattribute__(forge_app, "_inst")
+ yield
+ object.__setattr__(forge_app, "_inst", previous_app)
+
+
[email protected](autouse=True)
+def _use_minimal_empty_profile_seed(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(browser_profiles_route, "_default_browser_profile_template_candidates", lambda: [])
+
+
+def _build_client(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ raise_server_exceptions: bool = False,
+) -> tuple[TestClient, SimpleNamespace]:
async def _fake_org() -> SimpleNamespace:
return SimpleNamespace(organization_id="org_oss")
mocks = SimpleNamespace(
get_session=AsyncMock(),
+ get_workflow_run=AsyncMock(),
+ get_workflow=AsyncMock(),
create_profile=AsyncMock(return_value=_profile()),
delete_db_profile=AsyncMock(),
+ hard_delete_db_profile=AsyncMock(),
retrieve_profile=AsyncMock(),
+ retrieve_session=AsyncMock(),
store_profile=AsyncMock(),
delete_profile_blob=AsyncMock(),
+ rate_limit_submit_run=AsyncMock(),
+ get_workflow_browser_session_storage_key=AsyncMock(return_value="wp_1"),
+ )
+
+ forge_app.set_app(
+ SimpleNamespace(
+ RATE_LIMITER=SimpleNamespace(rate_limit_submit_run=mocks.rate_limit_submit_run),
+ WORKFLOW_SERVICE=SimpleNamespace(
+ get_workflow_browser_session_storage_key=mocks.get_workflow_browser_session_storage_key,
+ ),
+ DATABASE=SimpleNamespace(
+ browser_sessions=SimpleNamespace(
+ get_persistent_browser_session=mocks.get_session,
+ create_browser_profile=mocks.create_profile,
+ delete_browser_profile=mocks.delete_db_profile,
+ hard_delete_browser_profile=mocks.hard_delete_db_profile,
+ ),
+ workflow_runs=SimpleNamespace(get_workflow_run=mocks.get_workflow_run),
+ workflows=SimpleNamespace(get_workflow=mocks.get_workflow),
+ ),
+ STORAGE=SimpleNamespace(
+ retrieve_browser_profile=mocks.retrieve_profile,
+ retrieve_browser_session=mocks.retrieve_session,
+ store_browser_profile=mocks.store_profile,
+ delete_browser_profile=mocks.delete_profile_blob,
+ ),
+ )
+ )
+
+ test_router = APIRouter()
+ test_router.add_api_route(
+ "/browser_profiles",
+ browser_profiles_route.create_browser_profile,
+ methods=["POST"],
+ response_model=BrowserProfile,
+ )
+ test_router.add_api_route(
+ "/browser_profiles/",
+ browser_profiles_route.create_browser_profile,
+ methods=["POST"],
+ response_model=BrowserProfile,
+ include_in_schema=False,
)
- monkeypatch.setattr(forge_app.DATABASE.browser_sessions, "get_persistent_browser_session", mocks.get_session)
- monkeypatch.setattr(forge_app.DATABASE.browser_sessions, "create_browser_profile", mocks.create_profile)
- monkeypatch.setattr(forge_app.DATABASE.browser_sessions, "delete_browser_profile", mocks.delete_db_profile)
- monkeypatch.setattr(forge_app.STORAGE, "retrieve_browser_profile", mocks.retrieve_profile)
- monkeypatch.setattr(forge_app.STORAGE, "store_browser_profile", mocks.store_profile)
- monkeypatch.setattr(forge_app.STORAGE, "delete_browser_profile", mocks.delete_profile_blob)
fastapi_app = FastAPI()
fastapi_app.dependency_overrides[org_auth_service.get_current_org] = _fake_org
- fastapi_app.include_router(routers_module.base_router, prefix="/v1")
+ fastapi_app.include_router(test_router, prefix="/v1")
@fastapi_app.exception_handler(SkyvernHTTPException)
async def _handle(request: Request, exc: SkyvernHTTPException) -> JSONResponse:
@@ -69,7 +131,319 @@ def _build_client(monkeypatch: pytest.MonkeyPatch) -> tuple[TestClient, SimpleNa
# raise_server_exceptions=False so an un-mapped error surfaces as a 500 response (as in prod)
# rather than propagating out of the TestClient — the failed-promote path re-raises after rollback.
- return TestClient(fastapi_app, raise_server_exceptions=False), mocks
+ return TestClient(fastapi_app, raise_server_exceptions=raise_server_exceptions), mocks
+
+
+def test_request_model_accepts_no_source() -> None:
+ request = CreateBrowserProfileRequest(name="fresh profile")
+
+ assert request.browser_session_id is None
+ assert request.workflow_run_id is None
+
+
+def test_request_model_rejects_both_sources() -> None:
+ with pytest.raises(ValidationError, match="Provide only one of browser_session_id or workflow_run_id"):
+ CreateBrowserProfileRequest(name="my profile", browser_session_id="pbs_1", workflow_run_id="wr_1")
+
+
+def test_request_model_rejects_whitespace_source_id() -> None:
+ with pytest.raises(ValidationError):
+ CreateBrowserProfileRequest(name="my profile", browser_session_id=" ")
+
+
+def test_whitespace_source_id_returns_422(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, mocks = _build_client(monkeypatch)
+
+ response = client.post("/v1/browser_profiles/", json={"name": "fresh profile", "browser_session_id": " "})
+
+ assert response.status_code == 422
+ mocks.create_profile.assert_not_awaited()
+ mocks.store_profile.assert_not_awaited()
+
+
+def _make_default_profile_template(
+ tmp_path: Path,
+ *,
+ name: str = "default_profile",
+ marker: str = "from-template",
+) -> Path:
+ template = tmp_path / name
+ (template / "Default").mkdir(parents=True)
+ (template / "Default" / "Preferences").write_text('{"profile": "template"}', encoding="utf-8")
+ (template / "Default" / "template-marker.txt").write_text(marker, encoding="utf-8")
+ (template / "Local State").write_text('{"local": "template"}', encoding="utf-8")
+ (template / "ShaderCache").mkdir()
+ (template / "ShaderCache" / "cache.bin").write_bytes(b"cache")
+ return template
+
+
+def test_create_empty_profile_stores_default_profile_seed(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ client, mocks = _build_client(monkeypatch)
+ template = _make_default_profile_template(tmp_path)
+ captured_directory: dict[str, str] = {}
+
+ async def _store_profile(**kwargs: str) -> None:
+ directory = Path(kwargs["directory"])
+ captured_directory["path"] = str(directory)
+ assert (directory / "Default" / "Preferences").read_text(encoding="utf-8") == '{"profile": "template"}'
+ assert (directory / "Default" / "template-marker.txt").read_text(encoding="utf-8") == "from-template"
+ assert (directory / "Local State").read_text(encoding="utf-8") == '{"local": "template"}'
+ assert not (directory / "ShaderCache").exists()
+
+ monkeypatch.setattr(browser_profiles_route, "_default_browser_profile_template_candidates", lambda: [template])
+ mocks.store_profile.side_effect = _store_profile
+
+ response = client.post("/v1/browser_profiles/", json={"name": "fresh profile", "description": "blank"})
+
+ assert response.status_code == 200
+ mocks.rate_limit_submit_run.assert_awaited_once_with("org_oss")
+ mocks.create_profile.assert_awaited_once_with(
+ organization_id="org_oss",
+ name="fresh profile",
+ description="blank",
+ )
+ mocks.store_profile.assert_awaited_once()
+ assert captured_directory["path"]
+ assert not Path(captured_directory["path"]).exists()
+ mocks.delete_db_profile.assert_not_awaited()
+ mocks.hard_delete_db_profile.assert_not_awaited()
+
+
+def test_default_profile_template_candidates_come_from_configured_directory(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ (tmp_path / "chrome").mkdir()
+ (tmp_path / "chrome_100").mkdir()
+ (tmp_path / "chrome_200").mkdir()
+ (tmp_path / "chrome_backup").mkdir()
+ (tmp_path / "chromium_150").mkdir()
+ (tmp_path / "firefox_999").mkdir()
+ monkeypatch.setattr(browser_profiles_route.settings, "DEFAULT_BROWSER_PROFILE_DIR", str(tmp_path))
+
+ assert _default_profile_template_candidates() == [
+ tmp_path,
+ tmp_path / "chrome_200",
+ tmp_path / "chrome_100",
+ tmp_path / "chrome",
+ tmp_path / "chromium_150",
+ tmp_path / "chromium",
+ ]
+
+
+def test_create_empty_profile_uses_latest_versioned_default_profile(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ client, mocks = _build_client(monkeypatch)
+ _make_default_profile_template(tmp_path, name="chrome_100", marker="old-template")
+ _make_default_profile_template(tmp_path, name="chrome_200", marker="new-template")
+
+ async def _store_profile(**kwargs: str) -> None:
+ directory = Path(kwargs["directory"])
+ assert (directory / "Default" / "template-marker.txt").read_text(encoding="utf-8") == "new-template"
+
+ monkeypatch.setattr(browser_profiles_route.settings, "DEFAULT_BROWSER_PROFILE_DIR", str(tmp_path))
+ monkeypatch.setattr(
+ browser_profiles_route,
+ "_default_browser_profile_template_candidates",
+ _default_profile_template_candidates,
+ )
+ mocks.store_profile.side_effect = _store_profile
+
+ response = client.post("/v1/browser_profiles/", json={"name": "fresh profile"})
+
+ assert response.status_code == 200
+ mocks.store_profile.assert_awaited_once()
+
+
+def test_create_empty_profile_falls_back_to_minimal_seed(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, mocks = _build_client(monkeypatch)
+ captured_directory: dict[str, str] = {}
+
+ async def _store_profile(**kwargs: str) -> None:
+ directory = Path(kwargs["directory"])
+ captured_directory["path"] = str(directory)
+ assert (directory / "Default" / "Preferences").read_text(encoding="utf-8") == "{}"
+ assert (directory / "Local State").read_text(encoding="utf-8") == "{}"
+
+ monkeypatch.setattr(browser_profiles_route, "_default_browser_profile_template_candidates", lambda: [])
+ mocks.store_profile.side_effect = _store_profile
+
+ response = client.post("/v1/browser_profiles/", json={"name": "fresh profile"})
+
+ assert response.status_code == 200
+ mocks.rate_limit_submit_run.assert_awaited_once_with("org_oss")
+ mocks.store_profile.assert_awaited_once()
+ assert captured_directory["path"]
+ assert not Path(captured_directory["path"]).exists()
+
+
+def test_create_empty_profile_rate_limit_failure_does_not_seed_or_create(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ client, mocks = _build_client(monkeypatch)
+ create_directory = Mock(side_effect=AssertionError("profile directory should not be created"))
+ mocks.rate_limit_submit_run.side_effect = HTTPException(status_code=429, detail="rate limited")
+ monkeypatch.setattr(browser_profiles_route, "_create_empty_browser_profile_directory", create_directory)
+
+ response = client.post("/v1/browser_profiles/", json={"name": "fresh profile"})
+
+ assert response.status_code == 429
+ create_directory.assert_not_called()
+ mocks.create_profile.assert_not_awaited()
+ mocks.store_profile.assert_not_awaited()
+
+
+def test_create_empty_profile_does_not_create_db_row_when_blank_directory_fails(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ client, mocks = _build_client(monkeypatch)
+
+ def _raise_directory_error() -> str:
+ raise RuntimeError("temp dir failed")
+
+ monkeypatch.setattr(browser_profiles_route, "_create_empty_browser_profile_directory", _raise_directory_error)
+
+ response = client.post("/v1/browser_profiles/", json={"name": "fresh profile"})
+
+ assert response.status_code == 500
+ mocks.create_profile.assert_not_awaited()
+ mocks.delete_db_profile.assert_not_awaited()
+ mocks.hard_delete_db_profile.assert_not_awaited()
+ mocks.store_profile.assert_not_awaited()
+
+
+def test_create_empty_profile_rolls_back_when_archive_store_fails(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, mocks = _build_client(monkeypatch)
+ mocks.store_profile.side_effect = RuntimeError("s3 upload failed")
+
+ response = client.post("/v1/browser_profiles/", json={"name": "fresh profile"})
+
+ assert response.status_code == 500
+ mocks.hard_delete_db_profile.assert_awaited_once_with("bp_new", organization_id="org_oss")
+ mocks.delete_db_profile.assert_not_awaited()
+
+
+def test_create_empty_profile_preserves_store_error_when_rollback_fails(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, mocks = _build_client(monkeypatch, raise_server_exceptions=True)
+ mocks.store_profile.side_effect = RuntimeError("s3 upload failed")
+ mocks.hard_delete_db_profile.side_effect = RuntimeError("db rollback failed")
+
+ with pytest.raises(RuntimeError, match="s3 upload failed"):
+ client.post("/v1/browser_profiles/", json={"name": "fresh profile"})
+
+ mocks.hard_delete_db_profile.assert_awaited_once_with("bp_new", organization_id="org_oss")
+ mocks.delete_db_profile.assert_not_awaited()
+
+
+def test_create_empty_profile_preserves_duplicate_name_handling(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, mocks = _build_client(monkeypatch)
+ mocks.create_profile.side_effect = IntegrityError("insert", {}, Exception("duplicate"))
+
+ response = client.post("/v1/browser_profiles/", json={"name": "my profile"})
+
+ assert response.status_code == 409
+ assert "already exists" in response.json()["detail"]
+ mocks.store_profile.assert_not_awaited()
+
+
+def test_create_profile_route_delegates_workflow_run_source(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, mocks = _build_client(monkeypatch)
+ calls: list[dict[str, str | None]] = []
+
+ async def _create_profile_from_workflow_run(**kwargs: str | None) -> BrowserProfile:
+ calls.append(kwargs)
+ return _profile()
+
+ monkeypatch.setattr(
+ browser_profiles_route,
+ "_create_profile_from_workflow_run",
+ _create_profile_from_workflow_run,
+ )
+
+ response = client.post(
+ "/v1/browser_profiles/",
+ json={"name": "my profile", "description": "from workflow", "workflow_run_id": "wr_1"},
+ )
+
+ assert response.status_code == 200
+ assert calls == [
+ {
+ "organization_id": "org_oss",
+ "name": "my profile",
+ "description": "from workflow",
+ "workflow_run_id": "wr_1",
+ }
+ ]
+ mocks.rate_limit_submit_run.assert_not_awaited()
+ mocks.get_workflow_run.assert_not_awaited()
+ mocks.store_profile.assert_not_awaited()
+
+
+async def test_create_profile_from_workflow_run_still_stores_workflow_archive(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _client, mocks = _build_client(monkeypatch)
+ mocks.get_workflow_run.return_value = SimpleNamespace(
+ workflow_id="wf_1",
+ workflow_permanent_id="wp_1",
+ )
+ mocks.get_workflow.return_value = SimpleNamespace(
+ workflow_permanent_id="wp_1",
+ persist_browser_session=True,
+ )
+ mocks.retrieve_session.return_value = "/tmp/workflow_session_dir"
+
+ profile = await browser_profiles_route._create_profile_from_workflow_run(
+ organization_id="org_oss",
+ name="my profile",
+ description=None,
+ workflow_run_id="wr_1",
+ )
+
+ assert profile == _profile()
+ mocks.retrieve_session.assert_awaited_once_with(
+ organization_id="org_oss",
+ workflow_permanent_id="wp_1",
+ )
+ mocks.store_profile.assert_awaited_once_with(
+ organization_id="org_oss",
+ profile_id="bp_new",
+ directory="/tmp/workflow_session_dir",
+ )
+
+
+async def test_failed_workflow_run_profile_creation_hard_deletes_half_created_profile(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _client, mocks = _build_client(monkeypatch)
+ mocks.get_workflow_run.return_value = SimpleNamespace(
+ workflow_id="wf_1",
+ workflow_permanent_id="wp_1",
+ )
+ mocks.get_workflow.return_value = SimpleNamespace(
+ workflow_permanent_id="wp_1",
+ persist_browser_session=True,
+ )
+ mocks.retrieve_session.return_value = "/tmp/workflow_session_dir"
+ mocks.store_profile.side_effect = RuntimeError("s3 upload failed")
+
+ with pytest.raises(RuntimeError, match="s3 upload failed"):
+ await browser_profiles_route._create_profile_from_workflow_run(
+ organization_id="org_oss",
+ name="my profile",
+ description=None,
+ workflow_run_id="wr_1",
+ )
+
+ mocks.hard_delete_db_profile.assert_awaited_once_with("bp_new", organization_id="org_oss")
+ mocks.delete_db_profile.assert_not_awaited()
def test_promote_deletes_source_session_blob(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -80,6 +454,7 @@ def test_promote_deletes_source_session_blob(monkeypatch: pytest.MonkeyPatch) ->
response = client.post("/v1/browser_profiles/", json={"name": "my profile", "browser_session_id": "pbs_1"})
assert response.status_code == 200
+ mocks.rate_limit_submit_run.assert_not_awaited()
mocks.store_profile.assert_awaited_once()
mocks.delete_profile_blob.assert_awaited_once_with(organization_id="org_oss", profile_id="pbs_1")
@@ -93,7 +468,8 @@ def test_failed_promote_does_not_delete_source_blob(monkeypatch: pytest.MonkeyPa
response = client.post("/v1/browser_profiles/", json={"name": "my profile", "browser_session_id": "pbs_1"})
assert response.status_code == 500
- mocks.delete_db_profile.assert_awaited_once() # rolled back the half-created profile
+ mocks.hard_delete_db_profile.assert_awaited_once_with("bp_new", organization_id="org_oss")
+ mocks.delete_db_profile.assert_not_awaited()
mocks.delete_profile_blob.assert_not_awaited() # never reap the source on a failed promote