Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Revert "[5/5] [SKY-7600] Frontend: rewrite RunHistory" (#5311)
Aaron Perez3a25fe553ec3
diff --git a/skyvern-frontend/src/hooks/useRunsQuery.ts b/skyvern-frontend/src/hooks/useRunsQuery.tsindex a66026cec..fc6ebdf30 100644--- a/skyvern-frontend/src/hooks/useRunsQuery.ts+++ b/skyvern-frontend/src/hooks/useRunsQuery.ts@@ -3,19 +3,13 @@ import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { useQuery } from "@tanstack/react-query";import { Status, Task, TriggerType, WorkflowRunApiResponse } from "@/api/types";-type QueryReturnType = Array<Task | WorkflowRunApiResponse>;-type UseQueryOptions = Omit<- Parameters<typeof useQuery<QueryReturnType>>[0],- "queryKey" | "queryFn"->;-type Props = {page?: number;pageSize?: number;statusFilters?: Array<Status>;triggerTypeFilters?: Array<TriggerType>;search?: string;-} & UseQueryOptions;+};function useRunsQuery({page = 1,diff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.pyindex 75a5ef980..541d1458c 100644--- a/skyvern/forge/sdk/db/agent_db.py+++ b/skyvern/forge/sdk/db/agent_db.py@@ -109,6 +109,8 @@ __all__ = ["AgentDB", "ScheduleLimitExceededError"]class AgentDB(BaseAlchemyDB):+ _background_tasks: set[asyncio.Task] = set() # noqa: RUF012+def __init__(self, database_string: str, debug_enabled: bool = False, db_engine: AsyncEngine | None = None) -> None:super().__init__(db_engine or _build_engine(database_string))self.debug_enabled = debug_enabled@@ -231,7 +233,25 @@ class AgentDB(BaseAlchemyDB):return await self.tasks.clear_task_failure_reason(*args, **kwargs)async def update_task(self, *args: Any, **kwargs: Any) -> Any:- return await self.tasks.update_task(*args, **kwargs)+ updated_task = await self.tasks.update_task(*args, **kwargs)++ # Best-effort fire-and-forget write-through to task_runs.+ # Mirrors the WorkflowService pattern — cron catches any missed syncs.+ status = kwargs.get("status")+ if status is not None:+ task = asyncio.create_task(+ self.workflow_params.sync_task_run_status(+ organization_id=updated_task.organization_id or "",+ run_id=updated_task.task_id,+ status=status.value,+ started_at=updated_task.started_at,+ finished_at=updated_task.finished_at,+ ),+ )+ self._background_tasks.add(task)+ task.add_done_callback(self._background_tasks.discard)++ return updated_taskasync def update_task_2fa_state(self, *args: Any, **kwargs: Any) -> Any:return await self.tasks.update_task_2fa_state(*args, **kwargs)@@ -450,25 +470,25 @@ class AgentDB(BaseAlchemyDB):return await self.workflow_params.retrieve_action_plan(*args, **kwargs)async def create_task_run(self, *args: Any, **kwargs: Any) -> Any:- return await self.tasks.create_task_run(*args, **kwargs)+ return await self.workflow_params.create_task_run(*args, **kwargs)async def update_task_run(self, *args: Any, **kwargs: Any) -> Any:- return await self.tasks.update_task_run(*args, **kwargs)+ return await self.workflow_params.update_task_run(*args, **kwargs)async def sync_task_run_status(self, *args: Any, **kwargs: Any) -> Any:- return await self.tasks.sync_task_run_status(*args, **kwargs)+ return await self.workflow_params.sync_task_run_status(*args, **kwargs)async def update_job_run_compute_cost(self, *args: Any, **kwargs: Any) -> Any:- return await self.tasks.update_job_run_compute_cost(*args, **kwargs)+ return await self.workflow_params.update_job_run_compute_cost(*args, **kwargs)async def cache_task_run(self, *args: Any, **kwargs: Any) -> Any:- return await self.tasks.cache_task_run(*args, **kwargs)+ return await self.workflow_params.cache_task_run(*args, **kwargs)async def get_cached_task_run(self, *args: Any, **kwargs: Any) -> Any:- return await self.tasks.get_cached_task_run(*args, **kwargs)+ return await self.workflow_params.get_cached_task_run(*args, **kwargs)async def get_run(self, *args: Any, **kwargs: Any) -> Any:- return await self.tasks.get_run(*args, **kwargs)+ return await self.workflow_params.get_run(*args, **kwargs)# -- Artifact delegates --diff --git a/skyvern/forge/sdk/db/mixins/tasks.py b/skyvern/forge/sdk/db/mixins/tasks.pyindex 7f42ee438..01fef36b7 100644--- a/skyvern/forge/sdk/db/mixins/tasks.py+++ b/skyvern/forge/sdk/db/mixins/tasks.py@@ -14,15 +14,13 @@ from skyvern.forge.sdk.db.models import (ActionModel,StepModel,TaskModel,- TaskRunModel,WorkflowRunModel,)from skyvern.forge.sdk.db.utils import convert_to_step, convert_to_task, hydrate_action, serialize_proxy_locationfrom skyvern.forge.sdk.models import Step, StepStatus-from skyvern.forge.sdk.schemas.runs import Runfrom skyvern.forge.sdk.schemas.tasks import OrderBy, SortDirection, Task, TaskStatusfrom skyvern.forge.sdk.utils.sanitization import sanitize_postgres_text-from skyvern.schemas.runs import ProxyLocationInput, RunStatus, RunType+from skyvern.schemas.runs import ProxyLocationInputfrom skyvern.schemas.steps import AgentStepOutputfrom skyvern.webeye.actions.actions import Action@@ -739,197 +737,3 @@ class TasksMixin:)await session.execute(stmt)await session.commit()-- async def sync_task_run_status(- self,- organization_id: str,- run_id: str,- status: str,- started_at: datetime | None = None,- finished_at: datetime | None = None,- ) -> None:- """Best-effort write-through: propagate status from source table to task_runs.-- Does NOT raise if the task_runs row is missing (race at creation time).- """- try:- async with self.Session() as session:- vals: dict[str, Any] = {"status": status}- if started_at is not None:- vals["started_at"] = started_at- if finished_at is not None:- vals["finished_at"] = finished_at- stmt = (- update(TaskRunModel)- .where(TaskRunModel.run_id == run_id)- .where(TaskRunModel.organization_id == organization_id)- .values(**vals)- )- await session.execute(stmt)- await session.commit()- except Exception:- LOG.warning(- "Best-effort task_run status sync failed",- run_id=run_id,- organization_id=organization_id,- status=status,- exc_info=True,- )-- @db_operation("create_task_run")- async def create_task_run(- self,- task_run_type: RunType,- organization_id: str,- run_id: str,- title: str | None = None,- url: str | None = None,- url_hash: str | None = None,- status: RunStatus | None = None,- workflow_permanent_id: str | None = None,- parent_workflow_run_id: str | None = None,- debug_session_id: str | None = None,- # script_run, started_at, finished_at are intentionally omitted here —- # they are set via update_task_run() after the run starts/finishes (PRs 2-5).- ) -> Run:- searchable_text = " ".join(filter(None, [title, url]))- async with self.Session() as session:- task_run = TaskRunModel(- task_run_type=task_run_type,- organization_id=organization_id,- run_id=run_id,- title=title,- url=url,- url_hash=url_hash,- status=status,- workflow_permanent_id=workflow_permanent_id,- parent_workflow_run_id=parent_workflow_run_id,- debug_session_id=debug_session_id,- searchable_text=searchable_text or None,- )- session.add(task_run)- await session.commit()- await session.refresh(task_run)- return Run.model_validate(task_run)-- @db_operation("update_task_run")- async def update_task_run(- self,- organization_id: str,- run_id: str,- title: str | None = None,- url: str | None = None,- url_hash: str | None = None,- status: str | None = None,- started_at: datetime | None = None,- finished_at: datetime | None = None,- ) -> None:- async with self.Session() as session:- task_run = (- await session.scalars(- select(TaskRunModel).filter_by(run_id=run_id).filter_by(organization_id=organization_id)- )- ).first()- if not task_run:- raise NotFoundError(f"TaskRun {run_id} not found")-- if title is not None:- task_run.title = title- if url is not None:- task_run.url = url- if url_hash is not None:- task_run.url_hash = url_hash- if status is not None:- task_run.status = status- if started_at is not None:- task_run.started_at = started_at- if finished_at is not None:- task_run.finished_at = finished_at-- # Recompute searchable_text when title or url changes- if title is not None or url is not None:- task_run.searchable_text = " ".join(filter(None, [task_run.title, task_run.url])) or None-- await session.commit()-- @db_operation("update_job_run_compute_cost")- async def update_job_run_compute_cost(- self,- organization_id: str,- run_id: str,- instance_type: str | None = None,- vcpu_millicores: int | None = None,- memory_mb: int | None = None,- duration_ms: int | None = None,- compute_cost: float | None = None,- ) -> None:- """Update compute cost metrics for a job run."""- async with self.Session() as session:- task_run = (- await session.scalars(- select(TaskRunModel).filter_by(run_id=run_id).filter_by(organization_id=organization_id)- )- ).first()- if not task_run:- LOG.warning(- "TaskRun not found for compute cost update",- run_id=run_id,- organization_id=organization_id,- )- return-- if instance_type is not None:- task_run.instance_type = instance_type- if vcpu_millicores is not None:- task_run.vcpu_millicores = vcpu_millicores- if memory_mb is not None:- task_run.memory_mb = memory_mb- if duration_ms is not None:- task_run.duration_ms = duration_ms- if compute_cost is not None:- task_run.compute_cost = compute_cost- await session.commit()-- @db_operation("cache_task_run")- async def cache_task_run(self, run_id: str, organization_id: str | None = None) -> Run:- async with self.Session() as session:- task_run = (- await session.scalars(- select(TaskRunModel).filter_by(organization_id=organization_id).filter_by(run_id=run_id)- )- ).first()- if task_run:- task_run.cached = True- await session.commit()- await session.refresh(task_run)- return Run.model_validate(task_run)- raise NotFoundError(f"Run {run_id} not found")-- @db_operation("get_cached_task_run")- async def get_cached_task_run(- self, task_run_type: RunType, url_hash: str | None = None, organization_id: str | None = None- ) -> Run | None:- async with self.Session() as session:- query = select(TaskRunModel)- if task_run_type:- query = query.filter_by(task_run_type=task_run_type)- if url_hash:- query = query.filter_by(url_hash=url_hash)- if organization_id:- query = query.filter_by(organization_id=organization_id)- query = query.filter_by(cached=True).order_by(TaskRunModel.created_at.desc())- task_run = (await session.scalars(query)).first()- return Run.model_validate(task_run) if task_run else None-- @db_operation("get_run")- async def get_run(- self,- run_id: str,- organization_id: str | None = None,- ) -> Run | None:- async with self.Session() as session:- query = select(TaskRunModel).filter_by(run_id=run_id)- if organization_id:- query = query.filter_by(organization_id=organization_id)- task_run = (await session.scalars(query)).first()- return Run.model_validate(task_run) if task_run else Nonediff --git a/skyvern/forge/sdk/db/mixins/workflow_parameters.py b/skyvern/forge/sdk/db/mixins/workflow_parameters.pyindex 059233d1e..5d691d0fa 100644--- a/skyvern/forge/sdk/db/mixins/workflow_parameters.py+++ b/skyvern/forge/sdk/db/mixins/workflow_parameters.py@@ -5,7 +5,7 @@ from datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Anyimport structlog-from sqlalchemy import select+from sqlalchemy import select, updatefrom skyvern.config import settingsfrom skyvern.forge.sdk.db._error_handling import db_operation@@ -24,6 +24,7 @@ from skyvern.forge.sdk.db.models import (OutputParameterModel,TaskGenerationModel,TaskModel,+ TaskRunModel,WorkflowCopilotChatMessageModel,WorkflowCopilotChatModel,WorkflowParameterModel,@@ -36,6 +37,7 @@ from skyvern.forge.sdk.db.utils import (hydrate_action,)from skyvern.forge.sdk.schemas.ai_suggestions import AISuggestion+from skyvern.forge.sdk.schemas.runs import Runfrom skyvern.forge.sdk.schemas.task_generations import TaskGenerationfrom skyvern.forge.sdk.schemas.tasks import Task, TaskStatusfrom skyvern.forge.sdk.schemas.workflow_copilot import (@@ -57,6 +59,7 @@ from skyvern.forge.sdk.workflow.models.parameter import (WorkflowParameter,WorkflowParameterType,)+from skyvern.schemas.runs import RunStatus, RunTypefrom skyvern.webeye.actions.actions import Actionif TYPE_CHECKING:@@ -564,3 +567,197 @@ class WorkflowParametersMixin:actions = (await session.scalars(query)).all()return [Action.model_validate(action) for action in actions]++ @db_operation("create_task_run")+ async def create_task_run(+ self,+ task_run_type: RunType,+ organization_id: str,+ run_id: str,+ title: str | None = None,+ url: str | None = None,+ url_hash: str | None = None,+ status: RunStatus | None = None,+ workflow_permanent_id: str | None = None,+ parent_workflow_run_id: str | None = None,+ debug_session_id: str | None = None,+ # script_run, started_at, finished_at are intentionally omitted here —+ # they are set via update_task_run() after the run starts/finishes (PRs 2-5).+ ) -> Run:+ searchable_text = " ".join(filter(None, [title, url]))+ async with self.Session() as session:+ task_run = TaskRunModel(+ task_run_type=task_run_type,+ organization_id=organization_id,+ run_id=run_id,+ title=title,+ url=url,+ url_hash=url_hash,+ status=status,+ workflow_permanent_id=workflow_permanent_id,+ parent_workflow_run_id=parent_workflow_run_id,+ debug_session_id=debug_session_id,+ searchable_text=searchable_text or None,+ )+ session.add(task_run)+ await session.commit()+ await session.refresh(task_run)+ return Run.model_validate(task_run)++ @db_operation("update_task_run")+ async def update_task_run(+ self,+ organization_id: str,+ run_id: str,+ title: str | None = None,+ url: str | None = None,+ url_hash: str | None = None,+ status: str | None = None,+ started_at: datetime | None = None,+ finished_at: datetime | None = None,+ ) -> None:+ async with self.Session() as session:+ task_run = (+ await session.scalars(+ select(TaskRunModel).filter_by(run_id=run_id).filter_by(organization_id=organization_id)+ )+ ).first()+ if not task_run:+ raise NotFoundError(f"TaskRun {run_id} not found")++ if title is not None:+ task_run.title = title+ if url is not None:+ task_run.url = url+ if url_hash is not None:+ task_run.url_hash = url_hash+ if status is not None:+ task_run.status = status+ if started_at is not None:+ task_run.started_at = started_at+ if finished_at is not None:+ task_run.finished_at = finished_at++ # Recompute searchable_text when title or url changes+ if title is not None or url is not None:+ task_run.searchable_text = " ".join(filter(None, [task_run.title, task_run.url])) or None++ await session.commit()++ async def sync_task_run_status(+ self,+ organization_id: str,+ run_id: str,+ status: str,+ started_at: datetime | None = None,+ finished_at: datetime | None = None,+ ) -> None:+ """Best-effort write-through: propagate status from source table to task_runs.++ Does NOT raise if the task_runs row is missing (race at creation time).+ """+ try:+ async with self.Session() as session:+ vals: dict[str, Any] = {"status": status}+ if started_at is not None:+ vals["started_at"] = started_at+ if finished_at is not None:+ vals["finished_at"] = finished_at+ stmt = (+ update(TaskRunModel)+ .where(TaskRunModel.run_id == run_id)+ .where(TaskRunModel.organization_id == organization_id)+ .values(**vals)+ )+ await session.execute(stmt)+ await session.commit()+ except Exception:+ LOG.warning(+ "Best-effort task_run status sync failed",+ run_id=run_id,+ organization_id=organization_id,+ status=status,+ exc_info=True,+ )++ @db_operation("update_job_run_compute_cost")+ async def update_job_run_compute_cost(+ self,+ organization_id: str,+ run_id: str,+ instance_type: str | None = None,+ vcpu_millicores: int | None = None,+ memory_mb: int | None = None,+ duration_ms: int | None = None,+ compute_cost: float | None = None,+ ) -> None:+ """Update compute cost metrics for a job run."""+ async with self.Session() as session:+ task_run = (+ await session.scalars(+ select(TaskRunModel).filter_by(run_id=run_id).filter_by(organization_id=organization_id)+ )+ ).first()+ if not task_run:+ LOG.warning(+ "TaskRun not found for compute cost update",+ run_id=run_id,+ organization_id=organization_id,+ )+ return++ if instance_type is not None:+ task_run.instance_type = instance_type+ if vcpu_millicores is not None:+ task_run.vcpu_millicores = vcpu_millicores+ if memory_mb is not None:+ task_run.memory_mb = memory_mb+ if duration_ms is not None:+ task_run.duration_ms = duration_ms+ if compute_cost is not None:+ task_run.compute_cost = compute_cost+ await session.commit()++ @db_operation("cache_task_run")+ async def cache_task_run(self, run_id: str, organization_id: str | None = None) -> Run:+ async with self.Session() as session:+ task_run = (+ await session.scalars(+ select(TaskRunModel).filter_by(organization_id=organization_id).filter_by(run_id=run_id)+ )+ ).first()+ if task_run:+ task_run.cached = True+ await session.commit()+ await session.refresh(task_run)+ return Run.model_validate(task_run)+ raise NotFoundError(f"Run {run_id} not found")++ @db_operation("get_cached_task_run")+ async def get_cached_task_run(+ self, task_run_type: RunType, url_hash: str | None = None, organization_id: str | None = None+ ) -> Run | None:+ async with self.Session() as session:+ query = select(TaskRunModel)+ if task_run_type:+ query = query.filter_by(task_run_type=task_run_type)+ if url_hash:+ query = query.filter_by(url_hash=url_hash)+ if organization_id:+ query = query.filter_by(organization_id=organization_id)+ query = query.filter_by(cached=True).order_by(TaskRunModel.created_at.desc())+ task_run = (await session.scalars(query)).first()+ return Run.model_validate(task_run) if task_run else None++ @db_operation("get_run")+ async def get_run(+ self,+ run_id: str,+ organization_id: str | None = None,+ ) -> Run | None:+ async with self.Session() as session:+ query = select(TaskRunModel).filter_by(run_id=run_id)+ if organization_id:+ query = query.filter_by(organization_id=organization_id)+ task_run = (await session.scalars(query)).first()+ return Run.model_validate(task_run) if task_run else Nonediff --git a/skyvern/forge/sdk/db/repositories/tasks.py b/skyvern/forge/sdk/db/repositories/tasks.pyindex 6e54aa086..889aa0ca8 100644--- a/skyvern/forge/sdk/db/repositories/tasks.py+++ b/skyvern/forge/sdk/db/repositories/tasks.py@@ -1,6 +1,5 @@from __future__ import annotations-import asynciofrom datetime import datetime, timedelta, timezonefrom typing import Any, Sequence@@ -16,15 +15,13 @@ from skyvern.forge.sdk.db.models import (ActionModel,StepModel,TaskModel,- TaskRunModel,WorkflowRunModel,)from skyvern.forge.sdk.db.utils import convert_to_step, convert_to_task, hydrate_action, serialize_proxy_locationfrom skyvern.forge.sdk.models import Step, StepStatus-from skyvern.forge.sdk.schemas.runs import Runfrom skyvern.forge.sdk.schemas.tasks import OrderBy, SortDirection, Task, TaskStatusfrom skyvern.forge.sdk.utils.sanitization import sanitize_postgres_text-from skyvern.schemas.runs import ProxyLocationInput, RunStatus, RunType+from skyvern.schemas.runs import ProxyLocationInputfrom skyvern.schemas.steps import AgentStepOutputfrom skyvern.webeye.actions.actions import Action@@ -32,8 +29,6 @@ LOG = structlog.get_logger()class TasksRepository(BaseRepository):- _background_tasks: set[asyncio.Task] = set() # noqa: RUF012-@db_operation("create_task")async def create_task(self,@@ -475,22 +470,6 @@ class TasksRepository(BaseRepository):updated_task = await self.get_task(task_id, organization_id=organization_id)if not updated_task:raise NotFoundError("Task not found")-- # Best-effort fire-and-forget write-through to task_runs.- # Mirrors the WorkflowService pattern — cron catches any missed syncs.- if status is not None:- bg = asyncio.create_task(- self.sync_task_run_status(- organization_id=updated_task.organization_id or "",- run_id=updated_task.task_id,- status=status.value,- started_at=updated_task.started_at,- finished_at=updated_task.finished_at,- ),- )- self._background_tasks.add(bg)- bg.add_done_callback(self._background_tasks.discard)-return updated_taskelse:raise NotFoundError("Task not found")@@ -750,197 +729,3 @@ class TasksRepository(BaseRepository):)await session.execute(stmt)await session.commit()-- async def sync_task_run_status(- self,- organization_id: str,- run_id: str,- status: str,- started_at: datetime | None = None,- finished_at: datetime | None = None,- ) -> None:- """Best-effort write-through: propagate status from source table to task_runs.-- Does NOT raise if the task_runs row is missing (race at creation time).- """- try:- async with self.Session() as session:- vals: dict[str, Any] = {"status": status}- if started_at is not None:- vals["started_at"] = started_at- if finished_at is not None:- vals["finished_at"] = finished_at- stmt = (- update(TaskRunModel)- .where(TaskRunModel.run_id == run_id)- .where(TaskRunModel.organization_id == organization_id)- .values(**vals)- )- await session.execute(stmt)- await session.commit()- except Exception:- LOG.warning(- "Best-effort task_run status sync failed",- run_id=run_id,- organization_id=organization_id,- status=status,- exc_info=True,- )-- @db_operation("create_task_run")- async def create_task_run(- self,- task_run_type: RunType,- organization_id: str,- run_id: str,- title: str | None = None,- url: str | None = None,- url_hash: str | None = None,- status: RunStatus | None = None,- workflow_permanent_id: str | None = None,- parent_workflow_run_id: str | None = None,- debug_session_id: str | None = None,- # script_run, started_at, finished_at are intentionally omitted here —- # they are set via update_task_run() after the run starts/finishes (PRs 2-5).- ) -> Run:- searchable_text = " ".join(filter(None, [title, url]))- async with self.Session() as session:- task_run = TaskRunModel(- task_run_type=task_run_type,- organization_id=organization_id,- run_id=run_id,- title=title,- url=url,- url_hash=url_hash,- status=status,- workflow_permanent_id=workflow_permanent_id,- parent_workflow_run_id=parent_workflow_run_id,- debug_session_id=debug_session_id,- searchable_text=searchable_text or None,- )- session.add(task_run)- await session.commit()- await session.refresh(task_run)- return Run.model_validate(task_run)-- @db_operation("update_task_run")- async def update_task_run(- self,- organization_id: str,- run_id: str,- title: str | None = None,- url: str | None = None,- url_hash: str | None = None,- status: str | None = None,- started_at: datetime | None = None,- finished_at: datetime | None = None,- ) -> None:- async with self.Session() as session:- task_run = (- await session.scalars(- select(TaskRunModel).filter_by(run_id=run_id).filter_by(organization_id=organization_id)- )- ).first()- if not task_run:- raise NotFoundError(f"TaskRun {run_id} not found")-- if title is not None:- task_run.title = title- if url is not None:- task_run.url = url- if url_hash is not None:- task_run.url_hash = url_hash- if status is not None:- task_run.status = status- if started_at is not None:- task_run.started_at = started_at- if finished_at is not None:- task_run.finished_at = finished_at-- # Recompute searchable_text when title or url changes- if title is not None or url is not None:- task_run.searchable_text = " ".join(filter(None, [task_run.title, task_run.url])) or None-- await session.commit()-- @db_operation("update_job_run_compute_cost")- async def update_job_run_compute_cost(- self,- organization_id: str,- run_id: str,- instance_type: str | None = None,- vcpu_millicores: int | None = None,- memory_mb: int | None = None,- duration_ms: int | None = None,- compute_cost: float | None = None,- ) -> None:- """Update compute cost metrics for a job run."""- async with self.Session() as session:- task_run = (- await session.scalars(- select(TaskRunModel).filter_by(run_id=run_id).filter_by(organization_id=organization_id)- )- ).first()- if not task_run:- LOG.warning(- "TaskRun not found for compute cost update",- run_id=run_id,- organization_id=organization_id,- )- return-- if instance_type is not None:- task_run.instance_type = instance_type- if vcpu_millicores is not None:- task_run.vcpu_millicores = vcpu_millicores- if memory_mb is not None:- task_run.memory_mb = memory_mb- if duration_ms is not None:- task_run.duration_ms = duration_ms- if compute_cost is not None:- task_run.compute_cost = compute_cost- await session.commit()-- @db_operation("cache_task_run")- async def cache_task_run(self, run_id: str, organization_id: str | None = None) -> Run:- async with self.Session() as session:- task_run = (- await session.scalars(- select(TaskRunModel).filter_by(organization_id=organization_id).filter_by(run_id=run_id)- )- ).first()- if task_run:- task_run.cached = True- await session.commit()- await session.refresh(task_run)- return Run.model_validate(task_run)- raise NotFoundError(f"Run {run_id} not found")-- @db_operation("get_cached_task_run")- async def get_cached_task_run(- self, task_run_type: RunType, url_hash: str | None = None, organization_id: str | None = None- ) -> Run | None:- async with self.Session() as session:- query = select(TaskRunModel)- if task_run_type:- query = query.filter_by(task_run_type=task_run_type)- if url_hash:- query = query.filter_by(url_hash=url_hash)- if organization_id:- query = query.filter_by(organization_id=organization_id)- query = query.filter_by(cached=True).order_by(TaskRunModel.created_at.desc())- task_run = (await session.scalars(query)).first()- return Run.model_validate(task_run) if task_run else None-- @db_operation("get_run")- async def get_run(- self,- run_id: str,- organization_id: str | None = None,- ) -> Run | None:- async with self.Session() as session:- query = select(TaskRunModel).filter_by(run_id=run_id)- if organization_id:- query = query.filter_by(organization_id=organization_id)- task_run = (await session.scalars(query)).first()- return Run.model_validate(task_run) if task_run else Nonediff --git a/skyvern/forge/sdk/db/repositories/workflow_parameters.py b/skyvern/forge/sdk/db/repositories/workflow_parameters.pyindex b48a43fc4..28ad01013 100644--- a/skyvern/forge/sdk/db/repositories/workflow_parameters.py+++ b/skyvern/forge/sdk/db/repositories/workflow_parameters.py@@ -5,7 +5,7 @@ from datetime import datetime, timedelta, timezonefrom typing import Anyimport structlog-from sqlalchemy import select+from sqlalchemy import select, updatefrom skyvern.config import settingsfrom skyvern.forge.sdk.db._error_handling import db_operation@@ -26,6 +26,7 @@ from skyvern.forge.sdk.db.models import (OutputParameterModel,TaskGenerationModel,TaskModel,+ TaskRunModel,WorkflowCopilotChatMessageModel,WorkflowCopilotChatModel,WorkflowParameterModel,@@ -38,6 +39,7 @@ from skyvern.forge.sdk.db.utils import (hydrate_action,)from skyvern.forge.sdk.schemas.ai_suggestions import AISuggestion+from skyvern.forge.sdk.schemas.runs import Runfrom skyvern.forge.sdk.schemas.task_generations import TaskGenerationfrom skyvern.forge.sdk.schemas.tasks import Task, TaskStatusfrom skyvern.forge.sdk.schemas.workflow_copilot import (@@ -59,6 +61,7 @@ from skyvern.forge.sdk.workflow.models.parameter import (WorkflowParameter,WorkflowParameterType,)+from skyvern.schemas.runs import RunStatus, RunTypefrom skyvern.webeye.actions.actions import ActionLOG = structlog.get_logger()@@ -561,3 +564,197 @@ class WorkflowParametersRepository(BaseRepository):actions = (await session.scalars(query)).all()return [Action.model_validate(action) for action in actions]++ @db_operation("create_task_run")+ async def create_task_run(+ self,+ task_run_type: RunType,+ organization_id: str,+ run_id: str,+ title: str | None = None,+ url: str | None = None,+ url_hash: str | None = None,+ status: RunStatus | None = None,+ workflow_permanent_id: str | None = None,+ parent_workflow_run_id: str | None = None,+ debug_session_id: str | None = None,+ # script_run, started_at, finished_at are intentionally omitted here —+ # they are set via update_task_run() after the run starts/finishes (PRs 2-5).+ ) -> Run:+ searchable_text = " ".join(filter(None, [title, url]))+ async with self.Session() as session:+ task_run = TaskRunModel(+ task_run_type=task_run_type,+ organization_id=organization_id,+ run_id=run_id,+ title=title,+ url=url,+ url_hash=url_hash,+ status=status,+ workflow_permanent_id=workflow_permanent_id,+ parent_workflow_run_id=parent_workflow_run_id,+ debug_session_id=debug_session_id,+ searchable_text=searchable_text or None,+ )+ session.add(task_run)+ await session.commit()+ await session.refresh(task_run)+ return Run.model_validate(task_run)++ @db_operation("update_task_run")+ async def update_task_run(+ self,+ organization_id: str,+ run_id: str,+ title: str | None = None,+ url: str | None = None,+ url_hash: str | None = None,+ status: str | None = None,+ started_at: datetime | None = None,+ finished_at: datetime | None = None,+ ) -> None:+ async with self.Session() as session:+ task_run = (+ await session.scalars(+ select(TaskRunModel).filter_by(run_id=run_id).filter_by(organization_id=organization_id)+ )+ ).first()+ if not task_run:+ raise NotFoundError(f"TaskRun {run_id} not found")++ if title is not None:+ task_run.title = title+ if url is not None:+ task_run.url = url+ if url_hash is not None:+ task_run.url_hash = url_hash+ if status is not None:+ task_run.status = status+ if started_at is not None:+ task_run.started_at = started_at+ if finished_at is not None:+ task_run.finished_at = finished_at++ # Recompute searchable_text when title or url changes+ if title is not None or url is not None:+ task_run.searchable_text = " ".join(filter(None, [task_run.title, task_run.url])) or None++ await session.commit()++ async def sync_task_run_status(+ self,+ organization_id: str,+ run_id: str,+ status: str,+ started_at: datetime | None = None,+ finished_at: datetime | None = None,+ ) -> None:+ """Best-effort write-through: propagate status from source table to task_runs.++ Does NOT raise if the task_runs row is missing (race at creation time).+ """+ try:+ async with self.Session() as session:+ vals: dict[str, Any] = {"status": status}+ if started_at is not None:+ vals["started_at"] = started_at+ if finished_at is not None:+ vals["finished_at"] = finished_at+ stmt = (+ update(TaskRunModel)+ .where(TaskRunModel.run_id == run_id)+ .where(TaskRunModel.organization_id == organization_id)+ .values(**vals)+ )+ await session.execute(stmt)+ await session.commit()+ except Exception:+ LOG.warning(+ "Best-effort task_run status sync failed",+ run_id=run_id,+ organization_id=organization_id,+ status=status,+ exc_info=True,+ )++ @db_operation("update_job_run_compute_cost")+ async def update_job_run_compute_cost(+ self,+ organization_id: str,+ run_id: str,+ instance_type: str | None = None,+ vcpu_millicores: int | None = None,+ memory_mb: int | None = None,+ duration_ms: int | None = None,+ compute_cost: float | None = None,+ ) -> None:+ """Update compute cost metrics for a job run."""+ async with self.Session() as session:+ task_run = (+ await session.scalars(+ select(TaskRunModel).filter_by(run_id=run_id).filter_by(organization_id=organization_id)+ )+ ).first()+ if not task_run:+ LOG.warning(+ "TaskRun not found for compute cost update",+ run_id=run_id,+ organization_id=organization_id,+ )+ return++ if instance_type is not None:+ task_run.instance_type = instance_type+ if vcpu_millicores is not None:+ task_run.vcpu_millicores = vcpu_millicores+ if memory_mb is not None:+ task_run.memory_mb = memory_mb+ if duration_ms is not None:+ task_run.duration_ms = duration_ms+ if compute_cost is not None:+ task_run.compute_cost = compute_cost+ await session.commit()++ @db_operation("cache_task_run")+ async def cache_task_run(self, run_id: str, organization_id: str | None = None) -> Run:+ async with self.Session() as session:+ task_run = (+ await session.scalars(+ select(TaskRunModel).filter_by(organization_id=organization_id).filter_by(run_id=run_id)+ )+ ).first()+ if task_run:+ task_run.cached = True+ await session.commit()+ await session.refresh(task_run)+ return Run.model_validate(task_run)+ raise NotFoundError(f"Run {run_id} not found")++ @db_operation("get_cached_task_run")+ async def get_cached_task_run(+ self, task_run_type: RunType, url_hash: str | None = None, organization_id: str | None = None+ ) -> Run | None:+ async with self.Session() as session:+ query = select(TaskRunModel)+ if task_run_type:+ query = query.filter_by(task_run_type=task_run_type)+ if url_hash:+ query = query.filter_by(url_hash=url_hash)+ if organization_id:+ query = query.filter_by(organization_id=organization_id)+ query = query.filter_by(cached=True).order_by(TaskRunModel.created_at.desc())+ task_run = (await session.scalars(query)).first()+ return Run.model_validate(task_run) if task_run else None++ @db_operation("get_run")+ async def get_run(+ self,+ run_id: str,+ organization_id: str | None = None,+ ) -> Run | None:+ async with self.Session() as session:+ query = select(TaskRunModel).filter_by(run_id=run_id)+ if organization_id:+ query = query.filter_by(organization_id=organization_id)+ task_run = (await session.scalars(query)).first()+ return Run.model_validate(task_run) if task_run else Nonediff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 749971426..4cf54cdf2 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -3655,11 +3655,12 @@ class WorkflowService:)# Best-effort fire-and-forget write-through to task_runs table.# Runs off the hot path so workflow status transitions stay fast.- bg = asyncio.create_task(+ # Hold a reference in _background_tasks so Python doesn't GC the task.+ task = asyncio.create_task(self._sync_task_run_from_workflow_run(workflow_run, workflow_run_id, status),)- self._background_tasks.add(bg)- bg.add_done_callback(self._background_tasks.discard)+ self._background_tasks.add(task)+ task.add_done_callback(self._background_tasks.discard)return workflow_rundiff --git a/tests/unit/test_task_run_status_sync.py b/tests/unit/test_task_run_status_sync.pyindex 5dde03e33..6b91dec7f 100644--- a/tests/unit/test_task_run_status_sync.py+++ b/tests/unit/test_task_run_status_sync.py@@ -19,14 +19,14 @@ def mock_session():def agent_db(mock_session):db = AgentDB.__new__(AgentDB)db.Session = MagicMock(return_value=mock_session)- # Set up tasks repository (sync_task_run_status delegates to self.tasks)- from skyvern.forge.sdk.db.repositories.tasks import TasksRepository-- tasks = TasksRepository.__new__(TasksRepository)- tasks.Session = MagicMock(return_value=mock_session)- tasks.debug_enabled = False- tasks._is_retryable_error_fn = None- db.tasks = tasks+ # Set up workflow_params with the same session factory for delegation+ from skyvern.forge.sdk.db.repositories.workflow_parameters import WorkflowParametersRepository++ wp = WorkflowParametersRepository.__new__(WorkflowParametersRepository)+ wp.Session = MagicMock(return_value=mock_session)+ wp.debug_enabled = False+ wp._is_retryable_error_fn = None+ db.workflow_params = wpreturn db