Skip to content

Automate browser based workflows with AI

Live Record Browser Interpretation (backend) (#6396)

Cindy Li7c9f500440a7
diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.py
index 59e1d99f1..8804370d4 100644
--- a/skyvern/forge/api_app.py
+++ b/skyvern/forge/api_app.py
@@ -45,6 +45,7 @@ from skyvern.forge.sdk.services.local_org_auth_token_service import (
fingerprint_token,
regenerate_local_api_key,
)
+from skyvern.services.browser_recording.session_registry import interpretation_registry
from skyvern.services.cleanup_service import start_cleanup_scheduler, stop_cleanup_scheduler
from skyvern.services.workflow_schedule_service import (
start_workflow_schedule_scheduler,
@@ -270,6 +271,7 @@ async def lifespan(fastapi_app: FastAPI) -> AsyncGenerator[None, Any]:
# Stop cleanup scheduler
await stop_workflow_schedule_scheduler()
await stop_cleanup_scheduler()
+ await interpretation_registry.stop_all()
if forge_app.api_app_shutdown_event:
LOG.info("Calling api app shutdown event")
diff --git a/skyvern/forge/sdk/routes/browser_sessions.py b/skyvern/forge/sdk/routes/browser_sessions.py
index be15f4149..5b0a0ff2c 100644
--- a/skyvern/forge/sdk/routes/browser_sessions.py
+++ b/skyvern/forge/sdk/routes/browser_sessions.py
@@ -292,6 +292,7 @@ async def process_recording(
browser_session_id=browser_session_id,
compressed_chunks=recording_request.compressed_chunks,
workflow_permanent_id=recording_request.workflow_permanent_id,
+ draft_steps=recording_request.draft_steps,
)
return ProcessBrowserSessionRecordingResponse(blocks=blocks, parameters=parameters)
diff --git a/skyvern/forge/sdk/routes/streaming/channels/message.py b/skyvern/forge/sdk/routes/streaming/channels/message.py
index 96d91dfcb..a0a538cae 100644
--- a/skyvern/forge/sdk/routes/streaming/channels/message.py
+++ b/skyvern/forge/sdk/routes/streaming/channels/message.py
@@ -19,6 +19,7 @@ import typing as t
import structlog
from fastapi import WebSocket, WebSocketDisconnect
+from pydantic import BaseModel
from starlette.websockets import WebSocketState
from websockets.exceptions import ConnectionClosedError
@@ -39,6 +40,8 @@ from skyvern.forge.sdk.routes.streaming.verify import (
from skyvern.forge.sdk.schemas.persistent_browser_sessions import AddressablePersistentBrowserSession
from skyvern.forge.sdk.utils.aio import collect
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun
+from skyvern.services.browser_recording.session_registry import interpretation_registry
+from skyvern.services.browser_recording.types import RecordingDraftStep, RecordingInterpretationUpdate
LOG = structlog.get_logger()
@@ -64,6 +67,7 @@ class MessageKind(enum.StrEnum):
GO_FORWARD = "go-forward"
NAVIGATE = "navigate"
RELOAD = "reload"
+ RECORDING_INTERPRETATION_UPDATE = "recording-interpretation-update"
SCREENSHOT = "screenshot"
TAKE_CONTROL = "take-control"
TAKE_SCREENSHOT = "take-screenshot"
@@ -106,6 +110,7 @@ MessageKinds = t.Literal[
MessageKind.GO_FORWARD,
MessageKind.NAVIGATE,
MessageKind.RELOAD,
+ MessageKind.RECORDING_INTERPRETATION_UPDATE,
MessageKind.SCREENSHOT,
MessageKind.TAKE_CONTROL,
MessageKind.TAKE_SCREENSHOT,
@@ -120,6 +125,8 @@ class Message:
@dataclasses.dataclass
class MessageInBeginExfiltration(Message):
kind: t.Literal[MessageKind.BEGIN_EXFILTRATION] = MessageKind.BEGIN_EXFILTRATION
+ workflow_permanent_id: str | None = None
+ live_interpretation_enabled: bool = False
@dataclasses.dataclass
@@ -234,6 +241,15 @@ class MessageOutExfiltratedEvent(Message):
timestamp: float = dataclasses.field(default_factory=lambda: 0.0) # seconds since epoch
+class MessageOutRecordingInterpretationUpdate(Message):
+ kind: t.Literal[MessageKind.RECORDING_INTERPRETATION_UPDATE] = MessageKind.RECORDING_INTERPRETATION_UPDATE
+ session_revision: int = 0
+ steps: list[RecordingDraftStep] = dataclasses.field(default_factory=list)
+ pending: bool = False
+ finalized: bool = False
+
+
@dataclasses.dataclass
class MessageOutTabInfo(Message):
kind: t.Literal[MessageKind.BROWSER_TABS] = MessageKind.BROWSER_TABS
@@ -261,7 +277,12 @@ MessageIn = (
MessageOut = (
- MessageOutBrowserUrl | MessageOutError | MessageOutExfiltratedEvent | MessageOutScreenshot | MessageOutTabInfo
+ MessageOutBrowserUrl
+ | MessageOutError
+ | MessageOutExfiltratedEvent
+ | MessageOutRecordingInterpretationUpdate
+ | MessageOutScreenshot
+ | MessageOutTabInfo
)
@@ -276,7 +297,11 @@ def reify_channel_message(data: dict) -> ChannelMessage:
text = data.get("text") or ""
return MessageInAskForClipboardResponse(text=text)
case MessageKind.BEGIN_EXFILTRATION:
- return MessageInBeginExfiltration()
+ workflow_permanent_id = data.get("workflow_permanent_id")
+ return MessageInBeginExfiltration(
+ workflow_permanent_id=workflow_permanent_id if isinstance(workflow_permanent_id, str) else None,
+ live_interpretation_enabled=bool(data.get("live_interpretation_enabled") or False),
+ )
case MessageKind.CEDE_CONTROL:
return MessageInCedeControl()
case MessageKind.CLEAR_ALL_DATA:
@@ -320,9 +345,15 @@ def message_to_dict(message: MessageOut) -> dict:
def convert_value(obj: t.Any) -> t.Any:
if isinstance(obj, enum.Enum):
return obj.value
+ if isinstance(obj, BaseModel):
+ return obj.model_dump(mode="json")
+ if isinstance(obj, list):
+ return [convert_value(item) for item in obj]
+ if isinstance(obj, dict):
+ return {key: convert_value(value) for key, value in obj.items()}
return obj
- return dataclasses.asdict(message, dict_factory=lambda x: {k: convert_value(v) for k, v in x})
+ return {key: convert_value(value) for key, value in dataclasses.asdict(message).items()}
@dataclasses.dataclass
@@ -506,6 +537,7 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
class_name = message_channel.class_name
exfiltration_channel: ExfiltrationChannel | None = None
+ live_interpretation_browser_session_id: str | None = None
async def send(message: MessageOut) -> None:
if message_channel.websocket.client_state != WebSocketState.CONNECTED:
@@ -523,6 +555,7 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
async def handle_data(data: dict | MessageOut) -> None:
nonlocal class_name
nonlocal exfiltration_channel
+ nonlocal live_interpretation_browser_session_id
message: ChannelMessage
if isinstance(data, MessageOut):
@@ -589,6 +622,34 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
)
return
+ browser_session_id = (
+ message_channel.browser_session.persistent_browser_session_id
+ if message_channel.browser_session
+ else None
+ )
+
+ if browser_session_id and message.workflow_permanent_id and message.live_interpretation_enabled:
+
+ def on_interpretation_update(update: RecordingInterpretationUpdate) -> None:
+ message_channel.send_nowait(
+ messages=[
+ MessageOutRecordingInterpretationUpdate(
+ session_revision=update.session_revision,
+ steps=update.steps,
+ pending=update.pending,
+ finalized=update.finalized,
+ )
+ ]
+ )
+
+ interpretation_registry.start_session(
+ browser_session_id=browser_session_id,
+ organization_id=message_channel.organization_id,
+ workflow_permanent_id=message.workflow_permanent_id,
+ on_update=on_interpretation_update,
+ )
+ live_interpretation_browser_session_id = browser_session_id
+
def on_event(events: list[ExfiltratedEvent]) -> None:
for event in events:
message_out_exfiltrated_event = MessageOutExfiltratedEvent(
@@ -601,6 +662,9 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
message_channel.send_nowait(messages=[message_out_exfiltrated_event])
+ if live_interpretation_browser_session_id:
+ interpretation_registry.ingest_events(live_interpretation_browser_session_id, events)
+
exfiltration_channel = await ExfiltrationChannel(
on_event=on_event,
vnc_channel=vnc_channel,
@@ -701,6 +765,9 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
await exfiltration_channel.stop()
exfiltration_channel = None
+ if live_interpretation_browser_session_id:
+ await interpretation_registry.stop_session(live_interpretation_browser_session_id)
+ live_interpretation_browser_session_id = None
case MessageKind.ERROR:
await send(message)
@@ -708,6 +775,9 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
case MessageKind.EXFILTRATED_EVENT:
await send(message)
+ case MessageKind.RECORDING_INTERPRETATION_UPDATE:
+ await send(message)
+
case MessageKind.GET_BROWSER_URL:
try:
async with execution_for_message_channel(message_channel) as execute:
@@ -853,6 +923,10 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
LOG.exception(f"{class_name} An exception occurred in loop message channel stream.", **message_channel.identity)
finally:
LOG.debug(f"{class_name} Closing the message channel stream.", **message_channel.identity)
+ if exfiltration_channel is not None:
+ await exfiltration_channel.stop()
+ if live_interpretation_browser_session_id:
+ await interpretation_registry.stop_session(live_interpretation_browser_session_id)
await message_channel.close(reason="loop-channel-closed")
diff --git a/skyvern/schemas/browser_sessions.py b/skyvern/schemas/browser_sessions.py
index 6ac2e5cd4..dc0f7561c 100644
--- a/skyvern/schemas/browser_sessions.py
+++ b/skyvern/schemas/browser_sessions.py
@@ -5,6 +5,7 @@ from skyvern.client.types.workflow_definition_yaml_parameters_item import Workfl
from skyvern.forge.sdk.schemas.persistent_browser_sessions import Extensions, PersistentBrowserType
from skyvern.schemas.docs.doc_strings import PROXY_LOCATION_DOC_STRING
from skyvern.schemas.runs import GeoTarget, ProxyLocationInput
+from skyvern.services.browser_recording.types import RecordingDraftStep
MIN_TIMEOUT = 5
MAX_TIMEOUT = 60 * 24 # 24 hours
@@ -62,6 +63,10 @@ class ProcessBrowserSessionRecordingRequest(BaseModel):
default="no-such-wpid",
description="Permanent ID of the workflow associated with the browser session recording.",
)
+ draft_steps: list[RecordingDraftStep] | None = Field(
+ default=None,
+ description="Optional live interpretation drafts to commit instead of reprocessing the compressed recording.",
+ )
class ProcessBrowserSessionRecordingResponse(BaseModel):
diff --git a/skyvern/services/browser_recording/interpretation.py b/skyvern/services/browser_recording/interpretation.py
new file mode 100644
index 000000000..4ad51550d
--- /dev/null
+++ b/skyvern/services/browser_recording/interpretation.py
@@ -0,0 +1,309 @@
+import asyncio
+import dataclasses
+import enum
+import typing as t
+
+import structlog
+
+import skyvern.services.browser_recording.state_machines as sm
+from skyvern.client.types.workflow_definition_yaml_blocks_item import (
+ WorkflowDefinitionYamlBlocksItem_Action,
+ WorkflowDefinitionYamlBlocksItem_GotoUrl,
+ WorkflowDefinitionYamlBlocksItem_Wait,
+)
+from skyvern.forge.sdk.routes.streaming.channels import exfiltration as streaming_exfiltration
+from skyvern.forge.sdk.routes.streaming.channels.exfiltration import ExfiltratedEventSource
+from skyvern.services.browser_recording.service import Processor
+from skyvern.services.browser_recording.types import (
+ Action,
+ ActionKind,
+ ExfiltratedCdpEvent,
+ ExfiltratedConsoleEvent,
+ ExfiltratedEvent,
+ OutputBlock,
+ RecordingDraftStep,
+ RecordingDraftStepEditableField,
+ RecordingDraftStepStatus,
+ RecordingInterpretationUpdate,
+)
+
+LOG = structlog.get_logger(__name__)
+
+INTERPRETATION_DEBOUNCE_SECONDS = 1.5
+SIGNIFICANT_CONSOLE_EVENT_TYPES = {
+ "blur",
+ "change",
+ "click",
+ "focus",
+ "input",
+ "keydown",
+ "keypress",
+}
+
+OnRecordingInterpretationUpdate = t.Callable[[RecordingInterpretationUpdate], None]
+
+
+def _source_value(source: ExfiltratedEventSource | str) -> str:
+ if isinstance(source, enum.Enum):
+ return str(source.value)
+ return str(source)
+
+
+def streaming_events_to_recording_events(
+ events: list[streaming_exfiltration.ExfiltratedEvent],
+) -> list[ExfiltratedEvent]:
+ reified_events: list[ExfiltratedEvent] = []
+
+ for event in events:
+ source = _source_value(event.source)
+ payload = dataclasses.asdict(event)
+ payload["source"] = source
+
+ try:
+ if source == "cdp":
+ reified_events.append(ExfiltratedCdpEvent(**payload))
+ elif source == "console":
+ reified_events.append(ExfiltratedConsoleEvent(**payload))
+ else:
+ LOG.debug("Skipping recording interpretation event with unsupported source", source=source)
+ except Exception:
+ LOG.debug(
+ "Skipping recording interpretation event that could not be reified",
+ source=source,
+ event_name=event.event_name,
+ exc_info=True,
+ )
+
+ return reified_events
+
+
+def event_should_trigger_interpretation(event: ExfiltratedEvent) -> bool:
+ if isinstance(event, ExfiltratedCdpEvent):
+ return event.event_name.startswith("nav:")
+
+ return event.params.type in SIGNIFICANT_CONSOLE_EVENT_TYPES
+
+
+def _extra_field(block: OutputBlock, field_name: str, fallback: t.Any) -> t.Any:
+ value = getattr(block, field_name, None)
+ if value is not None:
+ return value
+
+ model_extra = getattr(block, "model_extra", None)
+ if isinstance(model_extra, dict) and field_name in model_extra:
+ return model_extra[field_name]
+
+ return fallback
+
+
+def _draft_step_from_block(
+ *,
+ browser_session_id: str,
+ action_index: int,
+ action: Action,
+ block: OutputBlock,
+) -> RecordingDraftStep | None:
+ step_id = f"{browser_session_id}-recording-step-{action_index}"
+
+ if isinstance(block, WorkflowDefinitionYamlBlocksItem_Action):
+ return RecordingDraftStep(
+ step_id=step_id,
+ action_kind=action.kind,
+ block_type="action",
+ label=block.label,
+ title=block.title,
+ navigation_goal=block.navigation_goal,
+ url=action.url,
+ status=RecordingDraftStepStatus.READY,
+ editable_fields=[
+ RecordingDraftStepEditableField.LABEL,
+ RecordingDraftStepEditableField.TITLE,
+ RecordingDraftStepEditableField.NAVIGATION_GOAL,
+ ],
+ parameters=_extra_field(block, "parameters", []),
+ parameter_keys=block.parameter_keys or [],
+ )
+
+ if isinstance(block, WorkflowDefinitionYamlBlocksItem_GotoUrl):
+ return RecordingDraftStep(
+ step_id=step_id,
+ action_kind=ActionKind.URL_CHANGE,
+ block_type="goto_url",
+ label=block.label,
+ url=block.url,
+ status=RecordingDraftStepStatus.READY,
+ editable_fields=[
+ RecordingDraftStepEditableField.LABEL,
+ RecordingDraftStepEditableField.URL,
+ ],
+ )
+
+ if isinstance(block, WorkflowDefinitionYamlBlocksItem_Wait):
+ return RecordingDraftStep(
+ step_id=step_id,
+ action_kind=ActionKind.WAIT,
+ block_type="wait",
+ label=block.label,
+ wait_sec=block.wait_sec,
+ status=RecordingDraftStepStatus.READY,
+ editable_fields=[
+ RecordingDraftStepEditableField.LABEL,
+ RecordingDraftStepEditableField.WAIT_SEC,
+ ],
+ )
+
+ return None
+
+
+class RecordingInterpretationSession:
+ def __init__(
+ self,
+ *,
+ browser_session_id: str,
+ organization_id: str,
+ workflow_permanent_id: str,
+ on_update: OnRecordingInterpretationUpdate,
+ debounce_seconds: float = INTERPRETATION_DEBOUNCE_SECONDS,
+ ) -> None:
+ self.browser_session_id = browser_session_id
+ self.organization_id = organization_id
+ self.workflow_permanent_id = workflow_permanent_id
+ self.on_update = on_update
+ self.debounce_seconds = debounce_seconds
+ self.events: list[ExfiltratedEvent] = []
+ self.steps: list[RecordingDraftStep] = []
+ self.emitted_action_count = 0
+ self.session_revision = 0
+ self.pending = False
+ self.finalized = False
+ self._debounce_task: asyncio.Task[None] | None = None
+ self._interpret_lock = asyncio.Lock()
+ self._action_machines: list[sm.StateMachine] = [
+ sm.Click(),
+ sm.Hover(),
+ sm.InputText(),
+ sm.UrlChange(),
+ sm.Wait(),
+ ]
+ self._all_actions: list[Action] = []
+ self._processed_event_count = 0
+
+ def ingest_events(self, events: list[streaming_exfiltration.ExfiltratedEvent]) -> None:
+ reified_events = streaming_events_to_recording_events(events)
+ if not reified_events:
+ return
+
+ self.events.extend(reified_events)
+
+ if not any(event_should_trigger_interpretation(event) for event in reified_events):
+ return
+
+ self.pending = True
+ self.finalized = False
+ self._emit_update()
+ self._schedule_interpretation()
+
+ def cancel(self) -> None:
+ if self._debounce_task and not self._debounce_task.done():
+ self._debounce_task.cancel()
+ self._debounce_task = None
+
+ async def flush(self) -> list[RecordingDraftStep]:
+ self.cancel()
+ await self._interpret(finalized=True)
+ return self.steps
+
+ def _schedule_interpretation(self) -> None:
+ self.cancel()
+ self._debounce_task = asyncio.create_task(self._debounced_interpret())
+
+ async def _debounced_interpret(self) -> None:
+ try:
+ await asyncio.sleep(self.debounce_seconds)
+ await self._interpret(finalized=False)
+ except asyncio.CancelledError:
+ return
+ finally:
+ self._debounce_task = None
+
+ async def _interpret(self, *, finalized: bool) -> None:
+ async with self._interpret_lock:
+ processor = Processor(
+ self.browser_session_id,
+ self.organization_id,
+ self.workflow_permanent_id,
+ )
+
+ if self._processed_event_count < len(self.events):
+ new_events = self.events[self._processed_event_count :]
+ self._all_actions = processor.events_to_actions(
+ new_events,
+ machines=self._action_machines,
+ initial_actions=self._all_actions,
+ )
+ self._processed_event_count = len(self.events)
+
+ actions = self._all_actions
+ new_actions = actions[self.emitted_action_count :]
+
+ if not new_actions:
+ self.pending = False
+ self.finalized = finalized
+ self._emit_update()
+ return
+
+ try:
+ blocks = await processor.actions_to_blocks(new_actions)
+ except Exception:
+ self.pending = False
+ self.finalized = finalized
+ self._emit_update()
+ LOG.exception(
+ "Failed to interpret live browser recording actions",
+ browser_session_id=self.browser_session_id,
+ organization_id=self.organization_id,
+ workflow_permanent_id=self.workflow_permanent_id,
+ )
+ return
+
+ if len(blocks) < len(new_actions):
+ LOG.warning(
+ "Live interpretation produced fewer blocks than actions",
+ browser_session_id=self.browser_session_id,
+ action_count=len(new_actions),
+ block_count=len(blocks),
+ )
+
+ for offset, (action, block) in enumerate(zip(new_actions, blocks, strict=False)):
+ action_index = self.emitted_action_count + offset
+ draft_step = _draft_step_from_block(
+ browser_session_id=self.browser_session_id,
+ action_index=action_index,
+ action=action,
+ block=block,
+ )
+ if draft_step:
+ self.steps.append(draft_step)
+
+ self.emitted_action_count += len(blocks)
+ self.pending = False
+ self.finalized = finalized
+ self._emit_update()
+
+ def _emit_update(self) -> None:
+ self.session_revision += 1
+ update = RecordingInterpretationUpdate(
+ session_revision=self.session_revision,
+ steps=self.steps,
+ pending=self.pending,
+ finalized=self.finalized,
+ )
+
+ try:
+ self.on_update(update)
+ except Exception:
+ LOG.exception(
+ "Failed to emit recording interpretation update",
+ browser_session_id=self.browser_session_id,
+ organization_id=self.organization_id,
+ )
diff --git a/skyvern/services/browser_recording/service.py b/skyvern/services/browser_recording/service.py
index 24e2d17de..738cd4b22 100644
--- a/skyvern/services/browser_recording/service.py
+++ b/skyvern/services/browser_recording/service.py
@@ -2,6 +2,7 @@ import asyncio
import base64
import json
import pathlib
+import re
import typing as t
import zlib
@@ -26,6 +27,7 @@ from skyvern.services.browser_recording.types import (
ExfiltratedConsoleEvent,
ExfiltratedEvent,
OutputBlock,
+ RecordingDraftStep,
)
@@ -60,6 +62,21 @@ LOG = structlog.get_logger(__name__)
# avoid decompression bombs
MAX_BASE64_SIZE = 14 * 1024 * 1024 # ~10MB compressed + base64 overhead
+DEFAULT_DRAFT_ACTION_TITLE = "Browser Action"
+
+
+def normalize_recording_block_label(label: str | None, *, fallback: str) -> str:
+ candidate = (label or "").strip()
+ candidate = re.sub(r"\W+", "_", candidate)
+ candidate = re.sub(r"_+", "_", candidate).strip("_")
+
+ if not candidate:
+ return fallback
+
+ if not re.match(r"^[A-Za-z_]", candidate):
+ candidate = f"{fallback}_{candidate}"
+
+ return candidate
class Processor:
@@ -202,11 +219,12 @@ class Processor:
self,
events: list[ExfiltratedEvent],
machines: list[sm.StateMachine] | None = None,
+ initial_actions: list[Action] | None = None,
) -> list[Action]:
"""
Convert a list of `ExfiltratedEvent`s into `Action`s.
"""
- actions: list[Action] = []
+ actions: list[Action] = list(initial_actions or [])
machines = machines or [
sm.Click(),
@@ -330,6 +348,57 @@ class Processor:
return parameters
+ def drafts_to_blocks(self, draft_steps: list[RecordingDraftStep]) -> list[OutputBlock]:
+ """
+ Convert user-editable live recording drafts into workflow definition blocks.
+ """
+ blocks: list[OutputBlock] = []
+
+ for draft_step in draft_steps:
+ match draft_step.block_type:
+ case "action":
+ block = WorkflowDefinitionYamlBlocksItem_Action(
+ label=normalize_recording_block_label(draft_step.label, fallback="act"),
+ title=draft_step.title or DEFAULT_DRAFT_ACTION_TITLE,
+ navigation_goal=draft_step.navigation_goal or "",
+ error_code_mapping=None,
+ parameters=draft_step.parameters,
+ parameter_keys=draft_step.parameter_keys,
+ )
+ case "goto_url":
+ url = (draft_step.url or "").strip()
+ if not url:
+ LOG.warning(
+ "skipping draft goto_url block with empty URL",
+ draft_step=draft_step.model_dump(mode="json"),
+ **self.identity,
+ )
+ continue
+ block = WorkflowDefinitionYamlBlocksItem_GotoUrl(
+ label=normalize_recording_block_label(draft_step.label, fallback="goto_url"),
+ url=url,
+ )
+ case "wait":
+ wait_sec = max(
+ int(draft_step.wait_sec or 0),
+ int(ActionWait.MIN_DURATION_THRESHOLD_MS / 1000.0),
+ )
+ block = WorkflowDefinitionYamlBlocksItem_Wait(
+ label=normalize_recording_block_label(draft_step.label, fallback="wait"),
+ wait_sec=wait_sec,
+ )
+ case _:
+ LOG.warning(
+ "skipping unsupported draft block type",
+ draft_step=draft_step.model_dump(mode="json"),
+ **self.identity,
+ )
+ continue
+
+ blocks.append(block)
+
+ return self.dedupe_block_labels(blocks)
+
async def create_action_block(self, action: ActionBlockable) -> WorkflowDefinitionYamlBlocksItem_Action:
"""
Create a YAML action block from an `ActionBlockable`.
@@ -424,11 +493,22 @@ class Processor:
return block
async def process(
- self, compressed_chunks: list[str]
+ self,
+ compressed_chunks: list[str],
+ draft_steps: list[RecordingDraftStep] | None = None,
) -> tuple[list[OutputBlock], list[WorkflowDefinitionYamlParametersItem_Workflow]]:
"""
Process the compressed browser session recording into workflow definition blocks.
"""
+ if draft_steps:
+ LOG.info(
+ "record_browser.process_recording_drafts",
+ recording_draft_step_count=len(draft_steps),
+ **self.identity,
+ )
+ blocks = self.drafts_to_blocks(draft_steps)
+ parameters = self.blocks_to_parameters(blocks)
+ return blocks, parameters
events = self.compressed_chunks_to_events(compressed_chunks)
LOG.info(
@@ -451,6 +531,7 @@ class BrowserSessionRecordingService:
organization_id: str,
workflow_permanent_id: str,
compressed_chunks: list[str],
+ draft_steps: list[RecordingDraftStep] | None = None,
) -> tuple[list[OutputBlock], list[WorkflowDefinitionYamlParametersItem_Workflow]]:
"""
Process compressed browser session recording events into workflow definition blocks.
@@ -461,7 +542,7 @@ class BrowserSessionRecordingService:
workflow_permanent_id,
)
- return await processor.process(compressed_chunks)
+ return await processor.process(compressed_chunks, draft_steps=draft_steps)
async def smoke() -> None:
diff --git a/skyvern/services/browser_recording/session_registry.py b/skyvern/services/browser_recording/session_registry.py
new file mode 100644
index 000000000..5dd464eab
--- /dev/null
+++ b/skyvern/services/browser_recording/session_registry.py
@@ -0,0 +1,85 @@
+import asyncio
+import time
+
+import structlog
+
+from skyvern.forge.sdk.routes.streaming.channels.exfiltration import ExfiltratedEvent
+from skyvern.services.browser_recording.interpretation import (
+ OnRecordingInterpretationUpdate,
+ RecordingInterpretationSession,
+)
+from skyvern.services.browser_recording.types import RecordingDraftStep
+
+LOG = structlog.get_logger(__name__)
+
+SESSION_TTL_SECONDS = 60 * 30
+
+
+class RecordingInterpretationSessionRegistry:
+ def __init__(self) -> None:
+ self._sessions: dict[str, RecordingInterpretationSession] = {}
+ self._last_seen: dict[str, float] = {}
+
+ def start_session(
+ self,
+ *,
+ browser_session_id: str,
+ organization_id: str,
+ workflow_permanent_id: str,
+ on_update: OnRecordingInterpretationUpdate,
+ ) -> None:
+ self.discard_session(browser_session_id)
+ self._prune_expired_sessions()
+ self._sessions[browser_session_id] = RecordingInterpretationSession(
+ browser_session_id=browser_session_id,
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ on_update=on_update,
+ )
+ self._last_seen[browser_session_id] = time.monotonic()
+
+ def ingest_events(self, browser_session_id: str, events: list[ExfiltratedEvent]) -> None:
+ self._prune_expired_sessions()
+ session = self._sessions.get(browser_session_id)
+ if not session:
+ return
+
+ self._last_seen[browser_session_id] = time.monotonic()
+ session.ingest_events(events)
+
+ async def stop_session(self, browser_session_id: str) -> list[RecordingDraftStep]:
+ session = self._sessions.pop(browser_session_id, None)
+ self._last_seen.pop(browser_session_id, None)
+ if not session:
+ return []
+
+ try:
+ return await session.flush()
+ finally:
+ session.cancel()
+
+ def discard_session(self, browser_session_id: str) -> None:
+ session = self._sessions.pop(browser_session_id, None)
+ self._last_seen.pop(browser_session_id, None)
+ if session:
+ session.cancel()
+
+ def _prune_expired_sessions(self) -> None:
+ now = time.monotonic()
+ expired_session_ids = [
+ browser_session_id
+ for browser_session_id, last_seen in self._last_seen.items()
+ if now - last_seen > SESSION_TTL_SECONDS
+ ]
+ for browser_session_id in expired_session_ids:
+ LOG.info("Pruning stale recording interpretation session", browser_session_id=browser_session_id)
+ self.discard_session(browser_session_id)
+
+ async def stop_all(self) -> None:
+ await asyncio.gather(*(self.stop_session(browser_session_id) for browser_session_id in list(self._sessions)))
+
+
+# Process-local singleton. Requires sticky routing (or a single worker) so the message
+# WebSocket and interpretation session stay on the same API instance. Multi-pod deployments
+# without affinity need shared session storage (e.g. Redis).
+interpretation_registry = RecordingInterpretationSessionRegistry()
diff --git a/skyvern/services/browser_recording/types.py b/skyvern/services/browser_recording/types.py
index 647ee2697..c157484fe 100644
--- a/skyvern/services/browser_recording/types.py
+++ b/skyvern/services/browser_recording/types.py
@@ -6,7 +6,7 @@ import enum
import typing as t
from typing import Literal
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, Field
from skyvern.client.types.workflow_definition_yaml_blocks_item import (
WorkflowDefinitionYamlBlocksItem_Action,
@@ -23,6 +23,19 @@ class ActionKind(enum.StrEnum):
WAIT = "wait"
+class RecordingDraftStepStatus(enum.StrEnum):
+ INTERPRETING = "interpreting"
+ READY = "ready"
+
+
+class RecordingDraftStepEditableField(enum.StrEnum):
+ LABEL = "label"
+ TITLE = "title"
+ NAVIGATION_GOAL = "navigation_goal"
+ URL = "url"
+ WAIT_SEC = "wait_sec"
+
+
class ActionBase(BaseModel):
kind: ActionKind
# --
@@ -92,6 +105,28 @@ OutputBlock = t.Union[
]
+class RecordingDraftStep(BaseModel):
+ step_id: str
+ action_kind: ActionKind
+ block_type: Literal["action", "goto_url", "wait"]
+ label: str
+ title: str | None = None
+ navigation_goal: str | None = None
+ url: str | None = None
+ wait_sec: int | None = None
+ status: RecordingDraftStepStatus = RecordingDraftStepStatus.READY
+ editable_fields: list[RecordingDraftStepEditableField] = Field(default_factory=list)
+ parameters: list[dict[str, t.Any]] = Field(default_factory=list)
+ parameter_keys: list[str] = Field(default_factory=list)
+
+
+class RecordingInterpretationUpdate(BaseModel):
+ session_revision: int
+ steps: list[RecordingDraftStep] = Field(default_factory=list)
+ pending: bool = False
+ finalized: bool = False
+
+
class TargetInfo(BaseModel):
attached: bool | None = None
browserContextId: str | None = None
diff --git a/tests/unit/forge/sdk/routes/streaming/test_message_reify.py b/tests/unit/forge/sdk/routes/streaming/test_message_reify.py
index 885c6bfe8..4ee2a52f4 100644
--- a/tests/unit/forge/sdk/routes/streaming/test_message_reify.py
+++ b/tests/unit/forge/sdk/routes/streaming/test_message_reify.py
@@ -14,6 +14,7 @@ from skyvern.forge.sdk.routes.streaming.channels import message as message_modul
from skyvern.forge.sdk.routes.streaming.channels.execution import ExecutionChannel, LocalExecutionChannel
from skyvern.forge.sdk.routes.streaming.channels.message import (
MessageChannel,
+ MessageInBeginExfiltration,
MessageInClearAllData,
MessageInClearCookies,
MessageInClearHistory,
@@ -24,9 +25,12 @@ from skyvern.forge.sdk.routes.streaming.channels.message import (
MessageInReload,
MessageInTakeScreenshot,
MessageKind,
+ MessageOutRecordingInterpretationUpdate,
loop_stream_messages,
+ message_to_dict,
reify_channel_message,
)
+from skyvern.services.browser_recording.types import ActionKind, RecordingDraftStep
class TestReifyChannelMessage:
@@ -86,6 +90,45 @@ class TestReifyChannelMessage:
with pytest.raises(ValueError):
reify_channel_message({"kind": "totally-not-a-real-kind"})
+ def test_begin_exfiltration_carries_live_interpretation_context(self) -> None:
+ msg = reify_channel_message(
+ {
+ "kind": "begin-exfiltration",
+ "workflow_permanent_id": "wpid_123",
+ "live_interpretation_enabled": True,
+ }
+ )
+
+ assert isinstance(msg, MessageInBeginExfiltration)
+ assert msg.workflow_permanent_id == "wpid_123"
+ assert msg.live_interpretation_enabled is True
+
+
+class TestMessageSerialization:
+ def test_recording_interpretation_update_serializes_pydantic_steps(self) -> None:
+ message = MessageOutRecordingInterpretationUpdate(
+ session_revision=2,
+ pending=False,
+ finalized=True,
+ steps=[
+ RecordingDraftStep(
+ step_id="step-1",
+ action_kind=ActionKind.CLICK,
+ block_type="action",
+ label="click_submit",
+ title="Click submit",
+ navigation_goal="Click submit",
+ )
+ ],
+ )
+
+ serialized = message_to_dict(message)
+
+ assert serialized["kind"] == "recording-interpretation-update"
+ assert serialized["session_revision"] == 2
+ assert serialized["finalized"] is True
+ assert serialized["steps"][0]["action_kind"] == "click"
+
class TestExecutionChannelHelpers:
@pytest.mark.asyncio
diff --git a/tests/unit/test_browser_recording_interpretation.py b/tests/unit/test_browser_recording_interpretation.py
new file mode 100644
index 000000000..3fc548d01
--- /dev/null
+++ b/tests/unit/test_browser_recording_interpretation.py
@@ -0,0 +1,278 @@
+from __future__ import annotations
+
+import asyncio
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from skyvern.client.types.workflow_definition_yaml_blocks_item import WorkflowDefinitionYamlBlocksItem_Wait
+from skyvern.forge.sdk.routes.streaming.channels.exfiltration import ExfiltratedEvent as StreamingExfiltratedEvent
+from skyvern.forge.sdk.routes.streaming.channels.exfiltration import (
+ ExfiltratedEventSource as StreamingExfiltratedEventSource,
+)
+from skyvern.services.browser_recording.interpretation import (
+ RecordingInterpretationSession,
+ streaming_events_to_recording_events,
+)
+from skyvern.services.browser_recording.service import Processor
+from skyvern.services.browser_recording.types import (
+ ActionKind,
+ ExfiltratedConsoleEvent,
+ RecordingDraftStep,
+)
+
+ORG_ID = "org_123"
+PBS_ID = "pbs_123"
+WP_ID = "wpid_123"
+
+
+def test_streaming_console_event_reifies_for_recording_processor() -> None:
+ event = StreamingExfiltratedEvent(
+ event_name="user_interaction",
+ source=StreamingExfiltratedEventSource.CONSOLE,
+ timestamp=1234.0,
+ params={
+ "type": "click",
+ "url": "https://example.com",
+ "timestamp": 1234.0,
+ "target": {
+ "tagName": "BUTTON",
+ "id": "submit",
+ "text": ["Submit"],
+ "skyId": "sky-1",
+ },
+ "mousePosition": {"xp": 0.5, "yp": 0.5},
+ "activeElement": {"tagName": "BUTTON"},
+ "window": {
+ "height": 800,
+ "width": 1200,
+ "scrollX": 0,
+ "scrollY": 0,
+ },
+ },
+ )
+
+ reified = streaming_events_to_recording_events([event])
+
+ assert len(reified) == 1
+ assert isinstance(reified[0], ExfiltratedConsoleEvent)
+ assert reified[0].params.target.skyId == "sky-1"
+
+
+def test_drafts_to_blocks_preserves_action_parameters_and_sanitizes_duplicate_labels() -> None:
+ processor = Processor(PBS_ID, ORG_ID, WP_ID)
+ parameter = {
+ "key": "customer_name",
+ "workflow_parameter_type": "string",
+ "default_value": "",
+ "description": "",
+ }
+ drafts = [
+ RecordingDraftStep(
+ step_id="step-1",
+ action_kind=ActionKind.CLICK,
+ block_type="action",
+ label="123 Submit!",
+ title="Submit form",
+ navigation_goal="Click submit",
+ parameters=[parameter],
+ parameter_keys=["customer_name"],
+ ),
+ RecordingDraftStep(
+ step_id="step-2",
+ action_kind=ActionKind.INPUT_TEXT,
+ block_type="action",
+ label="123 Submit!",
+ title="Type name",
+ navigation_goal="Type the customer name",
+ parameters=[parameter],
+ parameter_keys=["customer_name"],
+ ),
+ ]
+
+ blocks = processor.drafts_to_blocks(drafts)
+ parameters = processor.blocks_to_parameters(blocks)
+
+ assert [block.label for block in blocks] == ["act_123_Submit", "act_123_Submit_0"]
+ assert blocks[0].parameters == [parameter]
+ assert blocks[0].parameter_keys == ["customer_name"]
+ assert [parameter.key for parameter in parameters] == ["customer_name"]
+
+
+def test_drafts_to_blocks_skips_empty_goto_url() -> None:
+ processor = Processor(PBS_ID, ORG_ID, WP_ID)
+ drafts = [
+ RecordingDraftStep(
+ step_id="step-1",
+ action_kind=ActionKind.URL_CHANGE,
+ block_type="goto_url",
+ label="visit",
+ url="",
+ )
+ ]
+
+ assert processor.drafts_to_blocks(drafts) == []
+
+
+async def test_processor_process_uses_draft_steps_without_compressed_chunks() -> None:
+ processor = Processor(PBS_ID, ORG_ID, WP_ID)
+ drafts = [
+ RecordingDraftStep(
+ step_id="step-1",
+ action_kind=ActionKind.WAIT,
+ block_type="wait",
+ label="wait",
+ wait_sec=2,
+ )
+ ]
+
+ blocks, parameters = await processor.process([], draft_steps=drafts)
+
+ assert len(blocks) == 1
+ assert blocks[0].block_type == "wait"
+ assert blocks[0].wait_sec == 5
+ assert parameters == []
+
+
+def _click_streaming_event(*, timestamp: float = 1234.0) -> StreamingExfiltratedEvent:
+ return StreamingExfiltratedEvent(
+ event_name="user_interaction",
+ source=StreamingExfiltratedEventSource.CONSOLE,
+ timestamp=timestamp,
+ params={
+ "type": "click",
+ "url": "https://example.com",
+ "timestamp": timestamp,
+ "target": {
+ "tagName": "BUTTON",
+ "id": "submit",
+ "text": ["Submit"],
+ "skyId": "sky-1",
+ },
+ "mousePosition": {"xp": 0.5, "yp": 0.5},
+ "activeElement": {"tagName": "BUTTON"},
+ "window": {
+ "height": 800,
+ "width": 1200,
+ "scrollX": 0,
+ "scrollY": 0,
+ },
+ },
+ )
+
+
+async def test_recording_interpretation_session_reschedules_debounce_on_new_events(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ interpret_calls = 0
+
+ async def fake_interpret(self: RecordingInterpretationSession, *, finalized: bool) -> None:
+ nonlocal interpret_calls
+ interpret_calls += 1
+ self.pending = False
+ self.finalized = finalized
+
+ monkeypatch.setattr(RecordingInterpretationSession, "_interpret", fake_interpret)
+
+ session = RecordingInterpretationSession(
+ browser_session_id=PBS_ID,
+ organization_id=ORG_ID,
+ workflow_permanent_id=WP_ID,
+ on_update=lambda _: None,
+ debounce_seconds=60,
+ )
+ session.ingest_events([_click_streaming_event()])
+ first_task = session._debounce_task
+ session.ingest_events([_click_streaming_event(timestamp=1235.0)])
+ await asyncio.sleep(0)
+
+ assert first_task is not None
+ assert first_task.cancelled() or first_task.cancelling()
+ assert session._debounce_task is not None
+ assert session._debounce_task is not first_task
+ assert interpret_calls == 0
+
+ session.cancel()
+ await asyncio.sleep(0)
+
+
+async def test_recording_interpretation_session_cancel_clears_debounce_task() -> None:
+ session = RecordingInterpretationSession(
+ browser_session_id=PBS_ID,
+ organization_id=ORG_ID,
+ workflow_permanent_id=WP_ID,
+ on_update=lambda _: None,
+ debounce_seconds=60,
+ )
+ session.ingest_events([_click_streaming_event()])
+
+ assert session._debounce_task is not None
+ session.cancel()
+ assert session._debounce_task is None
+ await asyncio.sleep(0)
+
+
+async def test_recording_interpretation_session_flush_cancels_debounce(monkeypatch: pytest.MonkeyPatch) -> None:
+ debounce_started = asyncio.Event()
+ allow_debounce_finish = asyncio.Event()
+
+ async def fake_debounced_interpret(self: RecordingInterpretationSession) -> None:
+ debounce_started.set()
+ await allow_debounce_finish.wait()
+
+ monkeypatch.setattr(RecordingInterpretationSession, "_debounced_interpret", fake_debounced_interpret)
+
+ flush_calls = 0
+
+ async def fake_interpret(self: RecordingInterpretationSession, *, finalized: bool) -> None:
+ nonlocal flush_calls
+ flush_calls += 1
+ self.pending = False
+ self.finalized = finalized
+
+ monkeypatch.setattr(RecordingInterpretationSession, "_interpret", fake_interpret)
+
+ session = RecordingInterpretationSession(
+ browser_session_id=PBS_ID,
+ organization_id=ORG_ID,
+ workflow_permanent_id=WP_ID,
+ on_update=lambda _: None,
+ )
+ session.ingest_events([_click_streaming_event()])
+ await debounce_started.wait()
+
+ await session.flush()
+
+ assert flush_calls == 1
+ assert session._debounce_task is None
+
+
+async def test_recording_interpretation_session_advances_only_matched_blocks(monkeypatch: pytest.MonkeyPatch) -> None:
+ wait_block = WorkflowDefinitionYamlBlocksItem_Wait(label="wait", wait_sec=5)
+ processor = MagicMock()
+ processor.events_to_actions.return_value = [MagicMock(), MagicMock()]
+ processor.actions_to_blocks = AsyncMock(return_value=[wait_block])
+ monkeypatch.setattr(
+ "skyvern.services.browser_recording.interpretation.Processor",
+ lambda *args, **kwargs: processor,
+ )
+
+ session = RecordingInterpretationSession(
+ browser_session_id=PBS_ID,
+ organization_id=ORG_ID,
+ workflow_permanent_id=WP_ID,
+ on_update=lambda _: None,
+ )
+ session.events = [MagicMock(), MagicMock()]
+ session._processed_event_count = len(session.events)
+ session._all_actions = processor.events_to_actions.return_value
+
+ await session._interpret(finalized=False)
+
+ assert session.emitted_action_count == 1
+ assert len(session.steps) == 1