From df0f6e411e30ecca57dac1bc2128232a5703fd95 Mon Sep 17 00:00:00 2001 From: tudormatei Date: Wed, 4 Nov 2026 18:34:02 +0200 Subject: [PATCH 1/4] feat(cli): keep coded agents' workspace files across suspend and resume Coded agents lose the files they write when a job suspends, because nothing wraps them in HydrationRuntime. A factory can now opt in with UiPathRuntimeFactorySettings.managed_workspace, and run, debug and each eval item then get a workspace folder that is uploaded as job attachments on suspend and restored on resume. Only job runs are wrapped: only jobs resume in a new process, and outside a job there are no credentials to build the attachments client. A conversational run also uploads after a successful exchange, because the next exchange resumes the same job. Hydration sits outside governance, whose dispose does not reach the inner runtime, so the temporary folder is still removed. Co-Authored-By: Claude Opus 5.5 --- packages/uipath/src/uipath/_cli/cli_debug.py | 10 + packages/uipath/src/uipath/_cli/cli_run.py | 10 + .../src/uipath/_utils/_managed_workspace.py | 73 +++++++ .../uipath/src/uipath/eval/runtime/runtime.py | 13 +- packages/uipath/tests/cli/conftest.py | 8 + .../test_eval_runtime_managed_workspace.py | 93 +++++++++ .../tests/cli/test_managed_workspace.py | 148 ++++++++++++++ .../cli/test_managed_workspace_commands.py | 160 +++++++++++++++ .../uipath/tests/cli/utils/workspace_fakes.py | 185 ++++++++++++++++++ 9 files changed, 699 insertions(+), 1 deletion(-) create mode 100644 packages/uipath/src/uipath/_utils/_managed_workspace.py create mode 100644 packages/uipath/tests/cli/eval/test_eval_runtime_managed_workspace.py create mode 100644 packages/uipath/tests/cli/test_managed_workspace.py create mode 100644 packages/uipath/tests/cli/test_managed_workspace_commands.py create mode 100644 packages/uipath/tests/cli/utils/workspace_fakes.py diff --git a/packages/uipath/src/uipath/_cli/cli_debug.py b/packages/uipath/src/uipath/_cli/cli_debug.py index 5d67a0d51..bf513f69d 100644 --- a/packages/uipath/src/uipath/_cli/cli_debug.py +++ b/packages/uipath/src/uipath/_cli/cli_debug.py @@ -9,6 +9,7 @@ from uipath._cli._utils._debug import setup_debugging from uipath._cli._utils._studio_project import StudioClient from uipath._cli._utils._tracing import create_trace_manager +from uipath._utils._managed_workspace import wrap_with_managed_workspace from uipath.eval.mocks import SimulationConfig, UiPathMockRuntime, build_mocking_context from uipath.eval.mocks._mock_runtime import load_simulation_config from uipath.eval.mocks._simulation_model import get_agent_max_tokens @@ -229,6 +230,15 @@ async def execute_debug_runtime(): runtime_id=governance_runtime_id, ) + runtime = await wrap_with_managed_workspace( + runtime, + factory=factory, + settings=factory_settings, + runtime_id=governance_runtime_id, + job_id=ctx.job_id, + conversation_id=ctx.conversation_id, + ) + delegate = runtime if ctx.conversation_id and ctx.exchange_id: chat_bridge: UiPathChatProtocol = get_chat_bridge( diff --git a/packages/uipath/src/uipath/_cli/cli_run.py b/packages/uipath/src/uipath/_cli/cli_run.py index 5f9a1c0d3..57c3bbb72 100644 --- a/packages/uipath/src/uipath/_cli/cli_run.py +++ b/packages/uipath/src/uipath/_cli/cli_run.py @@ -8,6 +8,7 @@ from uipath._cli._utils._common import read_resource_overwrites_from_file from uipath._cli._utils._debug import setup_debugging from uipath._cli._utils._tracing import create_trace_manager +from uipath._utils._managed_workspace import wrap_with_managed_workspace from uipath.eval.mocks import SimulationConfig, UiPathMockRuntime, build_mocking_context from uipath.eval.mocks._simulation_model import get_agent_max_tokens from uipath.platform.common import ( @@ -307,6 +308,15 @@ async def execute() -> None: runtime_id=governance_runtime_id, ) + base_runtime = await wrap_with_managed_workspace( + base_runtime, + factory=factory, + settings=factory_settings, + runtime_id=governance_runtime_id, + job_id=ctx.job_id, + conversation_id=ctx.conversation_id, + ) + runtime = base_runtime if simulation_config: diff --git a/packages/uipath/src/uipath/_utils/_managed_workspace.py b/packages/uipath/src/uipath/_utils/_managed_workspace.py new file mode 100644 index 000000000..4c5c0f5a2 --- /dev/null +++ b/packages/uipath/src/uipath/_utils/_managed_workspace.py @@ -0,0 +1,73 @@ +"""Host-managed workspace persistence for runtimes that opt in. + +A factory opts in through ``UiPathRuntimeFactorySettings.managed_workspace``. +The host then gives each job run a workspace folder, exposed to agent code +through ``uipath.runtime.get_workspace_path()``, and persists the folder as +job attachments across suspend and resume. +""" + +from __future__ import annotations + +from uipath.platform import UiPath +from uipath.platform.common import UiPathConfig +from uipath.runtime import ( + HydrationPolicy, + ManagedWorkspace, + UiPathRuntimeFactoryProtocol, + UiPathRuntimeFactorySettings, + UiPathRuntimeProtocol, + WorkspaceRegistryStore, +) + +__all__ = ["wrap_with_managed_workspace"] + + +async def wrap_with_managed_workspace( + runtime: UiPathRuntimeProtocol, + *, + factory: UiPathRuntimeFactoryProtocol, + settings: UiPathRuntimeFactorySettings | None, + runtime_id: str, + job_id: str | None, + conversation_id: str | None = None, +) -> UiPathRuntimeProtocol: + """Wrap a runtime so its workspace survives suspend and resume. + + The runtime is returned unchanged unless the factory opts in, the run is a + job, and the factory has storage for the workspace registry. Files are + uploaded when the run suspends, and also when a conversational exchange + ends successfully, because the next exchange resumes the same job. + + Args: + runtime: Runtime returned by the factory. + factory: Factory that created the runtime; provides registry storage. + settings: The factory's settings. + runtime_id: Runtime id the runtime was created with. + job_id: Orchestrator job key, or ``None`` outside a job. + conversation_id: Conversation id for conversational runs. + + Returns: + The wrapped runtime, or ``runtime`` when no workspace applies. + """ + if settings is None or not settings.managed_workspace or not job_id: + return runtime + + storage = await factory.get_storage() + if storage is None: + return runtime + + managed = ManagedWorkspace( + services=UiPath, + runtime_id=runtime_id, + job_key=job_id, + folder_key=UiPathConfig.folder_key, + registry_store=WorkspaceRegistryStore(storage, runtime_id), + ) + return managed.wrap( + runtime, + policy=( + HydrationPolicy.SUSPEND_OR_SUCCESS + if conversation_id + else HydrationPolicy.SUSPEND_ONLY + ), + ) diff --git a/packages/uipath/src/uipath/eval/runtime/runtime.py b/packages/uipath/src/uipath/eval/runtime/runtime.py index 7cf6ff1ce..34ee03070 100644 --- a/packages/uipath/src/uipath/eval/runtime/runtime.py +++ b/packages/uipath/src/uipath/eval/runtime/runtime.py @@ -27,12 +27,14 @@ ) from pydantic import BaseModel, ValidationError +from uipath._utils._managed_workspace import wrap_with_managed_workspace from uipath.core.events import EventBus from uipath.core.tracing import UiPathTraceManager from uipath.runtime import ( UiPathExecuteOptions, UiPathExecutionRuntime, UiPathRuntimeFactoryProtocol, + UiPathRuntimeFactorySettings, UiPathRuntimeResult, UiPathRuntimeStatus, UiPathRuntimeStorageProtocol, @@ -352,12 +354,14 @@ def __init__( self.coverage = coverage.Coverage(branch=True) self._storage: UiPathRuntimeStorageProtocol | None = None + self._factory_settings: UiPathRuntimeFactorySettings | None = None async def __aenter__(self) -> UiPathEvalRuntime: """Async context manager entry - initialize storage and start coverage if enabled.""" if self.context.report_coverage: self.coverage.start() self._storage = await self.factory.get_storage() + self._factory_settings = await self.factory.get_settings() return self @@ -403,7 +407,7 @@ async def initiate_evaluation( f"Please run with a single evaluation using --eval-ids to specify one evaluation." ) - factory_settings = await self.factory.get_settings() + factory_settings = self._factory_settings agent_type = factory_settings.agent_type if factory_settings else None await self.event_bus.publish( @@ -1034,6 +1038,13 @@ async def execute_runtime( entrypoint=self.context.entrypoint or "", runtime_id=runtime_id, ) + eval_runtime = await wrap_with_managed_workspace( + eval_runtime, + factory=self.factory, + settings=self._factory_settings, + runtime_id=runtime_id, + job_id=self.context.job_id, + ) delegate = eval_runtime if mocking_context: diff --git a/packages/uipath/tests/cli/conftest.py b/packages/uipath/tests/cli/conftest.py index e84bf38f2..263c28723 100644 --- a/packages/uipath/tests/cli/conftest.py +++ b/packages/uipath/tests/cli/conftest.py @@ -3,6 +3,7 @@ import pytest from tests.cli.utils.project_details import ProjectDetails +from tests.cli.utils.workspace_fakes import FakeSdk @pytest.fixture @@ -29,3 +30,10 @@ def project_details() -> ProjectDetails: with open("tests/cli/mocks/pyproject.toml", "r") as file: data = file.read() return ProjectDetails.from_toml(data) + + +@pytest.fixture +def sdk(monkeypatch: pytest.MonkeyPatch) -> FakeSdk: + fake = FakeSdk() + monkeypatch.setattr("uipath._utils._managed_workspace.UiPath", lambda: fake) + return fake diff --git a/packages/uipath/tests/cli/eval/test_eval_runtime_managed_workspace.py b/packages/uipath/tests/cli/eval/test_eval_runtime_managed_workspace.py new file mode 100644 index 000000000..e2820cfc8 --- /dev/null +++ b/packages/uipath/tests/cli/eval/test_eval_runtime_managed_workspace.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +import uuid +from pathlib import Path +from typing import Any + +from tests.cli.utils.workspace_fakes import ( + OPTED_IN, + REGISTRY, + FakeSdk, + FileRuntime, + MemoryStorage, + WorkspaceFactory, +) +from uipath.core.events import EventBus +from uipath.core.tracing import UiPathTraceManager +from uipath.eval.helpers import EvalHelpers +from uipath.eval.runtime import UiPathEvalContext, evaluate +from uipath.eval.runtime.events import EvaluationEvents +from uipath.runtime import UiPathRuntimeFactorySettings, UiPathRuntimeStatus + +JOB_ID = str(uuid.uuid4()) +EVAL_SET = Path(__file__).parent / "evals" / "eval-sets" / "default.json" + + +async def _eval_context(items: int = 1) -> UiPathEvalContext: + evaluation_set, _ = EvalHelpers.load_eval_set(str(EVAL_SET)) + first = evaluation_set.evaluations[0] + evaluation_set.evaluations = [first] + [ + first.model_copy(update={"id": str(uuid.uuid4())}) for _ in range(items - 1) + ] + context = UiPathEvalContext() + context.execution_id = str(uuid.uuid4()) + context.job_id = JOB_ID + context.evaluation_set = evaluation_set + context.runtime_schema = await FileRuntime().get_schema() + context.evaluators = await EvalHelpers.load_evaluators( + str(EVAL_SET), evaluation_set, agent_model=None + ) + return context + + +def _suspending_factory( + storage: MemoryStorage, + settings: UiPathRuntimeFactorySettings | None = OPTED_IN, +) -> WorkspaceFactory: + return WorkspaceFactory( + FileRuntime(write="draft", status=UiPathRuntimeStatus.SUSPENDED), + storage=storage, + settings=settings, + ) + + +async def test_eval_uploads_each_suspended_item_workspace(sdk: FakeSdk) -> None: + context = await _eval_context(items=2) + storage = MemoryStorage() + + await evaluate( + _suspending_factory(storage), UiPathTraceManager(), context, EventBus() + ) + + item_ids = [item.id for item in context.evaluation_set.evaluations] + assert list(sdk.attachments.blobs.values()) == [b"draft"] * len(item_ids) + assert {key[0] for key in storage.values if key[1:] == REGISTRY} == set(item_ids) + + +async def test_eval_reads_factory_settings_once_for_all_items(sdk: FakeSdk) -> None: + factory = _suspending_factory(MemoryStorage()) + + await evaluate( + factory, UiPathTraceManager(), await _eval_context(items=2), EventBus() + ) + + assert factory.settings_reads == 1 + + +async def test_eval_set_run_carries_the_factory_agent_type(sdk: FakeSdk) -> None: + created: list[Any] = [] + event_bus = EventBus() + event_bus.subscribe(EvaluationEvents.CREATE_EVAL_SET_RUN, created.append) + settings = UiPathRuntimeFactorySettings( + managed_workspace=True, agent_type="uipath_coded" + ) + + await evaluate( + _suspending_factory(MemoryStorage(), settings), + UiPathTraceManager(), + await _eval_context(), + event_bus, + ) + await event_bus.wait_for_all() + + assert [event.agent_type for event in created] == ["uipath_coded"] diff --git a/packages/uipath/tests/cli/test_managed_workspace.py b/packages/uipath/tests/cli/test_managed_workspace.py new file mode 100644 index 000000000..fd6c9adbd --- /dev/null +++ b/packages/uipath/tests/cli/test_managed_workspace.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +from uuid import UUID, uuid4 + +import pytest + +from tests.cli.utils.workspace_fakes import ( + OPTED_IN, + FakeSdk, + FileRuntime, + MemoryStorage, + WorkspaceFactory, +) +from uipath._utils._managed_workspace import wrap_with_managed_workspace +from uipath.platform.constants import ENV_FOLDER_KEY +from uipath.runtime import ( + UiPathRuntimeFactorySettings, + UiPathRuntimeResult, + UiPathRuntimeStatus, +) + +JOB_ID = str(uuid4()) + + +async def _run( + runtime: FileRuntime, + storage: MemoryStorage | None, + *, + settings: UiPathRuntimeFactorySettings | None = OPTED_IN, + job_id: str | None = JOB_ID, + conversation_id: str | None = None, +) -> UiPathRuntimeResult: + wrapped = await wrap_with_managed_workspace( + runtime, + factory=WorkspaceFactory(runtime, storage=storage), + settings=settings, + runtime_id="runtime-1", + job_id=job_id, + conversation_id=conversation_id, + ) + try: + return await wrapped.execute() + finally: + await wrapped.dispose() + + +async def test_files_written_before_a_suspend_are_back_after_resume( + sdk: FakeSdk, +) -> None: + storage = MemoryStorage() + + await _run( + FileRuntime(write="draft", status=UiPathRuntimeStatus.SUSPENDED), storage + ) + resumed = await _run(FileRuntime(), storage) + + assert resumed.output == {"report": "draft"} + + +async def test_uploads_are_linked_to_the_job(sdk: FakeSdk) -> None: + await _run( + FileRuntime(write="draft", status=UiPathRuntimeStatus.SUSPENDED), + MemoryStorage(), + ) + + assert [job for job, _ in sdk.jobs.links] == [UUID(JOB_ID)] + assert list(sdk.attachments.blobs.values()) == [b"draft"] + + +async def test_attachment_calls_use_the_job_folder( + sdk: FakeSdk, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv(ENV_FOLDER_KEY, "folder-1") + storage = MemoryStorage() + + await _run( + FileRuntime(write="draft", status=UiPathRuntimeStatus.SUSPENDED), storage + ) + await _run(FileRuntime(), storage) + + assert sdk.attachments.folder_keys + assert sdk.jobs.folder_keys + assert set(sdk.attachments.folder_keys + sdk.jobs.folder_keys) == {"folder-1"} + + +async def test_successful_run_outside_a_conversation_uploads_nothing( + sdk: FakeSdk, +) -> None: + await _run(FileRuntime(write="final"), MemoryStorage()) + + assert sdk.attachments.blobs == {} + + +async def test_successful_exchange_in_a_conversation_keeps_files_for_the_next( + sdk: FakeSdk, +) -> None: + storage = MemoryStorage() + + await _run(FileRuntime(write="notes"), storage, conversation_id="conv-1") + next_exchange = await _run(FileRuntime(), storage, conversation_id="conv-1") + + assert next_exchange.output == {"report": "notes"} + + +async def test_dispose_removes_the_workspace_folder(sdk: FakeSdk) -> None: + runtime = FileRuntime(write="draft", status=UiPathRuntimeStatus.SUSPENDED) + + await _run(runtime, MemoryStorage()) + + assert runtime.workspace_path is not None + assert not runtime.workspace_path.exists() + + +@pytest.mark.parametrize( + ("settings", "job_id", "storage"), + [ + pytest.param(None, JOB_ID, MemoryStorage(), id="factory-without-settings"), + pytest.param( + UiPathRuntimeFactorySettings(), + JOB_ID, + MemoryStorage(), + id="factory-not-opted-in", + ), + pytest.param(OPTED_IN, None, MemoryStorage(), id="not-a-job"), + pytest.param(OPTED_IN, JOB_ID, None, id="factory-without-storage"), + ], +) +async def test_runtime_is_left_unwrapped( + settings: UiPathRuntimeFactorySettings | None, + job_id: str | None, + storage: MemoryStorage | None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + def no_sdk() -> FakeSdk: + raise AssertionError("the SDK must not be built for an unwrapped runtime") + + monkeypatch.setattr("uipath._utils._managed_workspace.UiPath", no_sdk) + runtime = FileRuntime() + + wrapped = await wrap_with_managed_workspace( + runtime, + factory=WorkspaceFactory(runtime, storage=storage), + settings=settings, + runtime_id="runtime-1", + job_id=job_id, + ) + + assert wrapped is runtime diff --git a/packages/uipath/tests/cli/test_managed_workspace_commands.py b/packages/uipath/tests/cli/test_managed_workspace_commands.py new file mode 100644 index 000000000..ee7267fe3 --- /dev/null +++ b/packages/uipath/tests/cli/test_managed_workspace_commands.py @@ -0,0 +1,160 @@ +from __future__ import annotations + +import json +import uuid +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any, AsyncIterator +from unittest.mock import patch + +import pytest +from click.testing import CliRunner + +from tests.cli.utils.workspace_fakes import ( + REGISTRY, + FakeSdk, + FileRuntime, + MemoryStorage, + WorkspaceFactory, +) +from uipath._cli import cli +from uipath._cli.middlewares import MiddlewareResult +from uipath.runtime import UiPathRuntimeStatus +from uipath.runtime.debug.detached import DetachedDebugBridge + +JOB_ID = str(uuid.uuid4()) + + +@pytest.fixture +def job_env(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("UIPATH_JOB_KEY", JOB_ID) + monkeypatch.setenv("UIPATH_TRACING_ENABLED", "false") + + +@asynccontextmanager +async def _no_resource_overwrites(*args: Any, **kwargs: Any) -> AsyncIterator[None]: + yield + + +def _continue() -> MiddlewareResult: + return MiddlewareResult(should_continue=True) + + +def _suspending_factory(storage: MemoryStorage) -> WorkspaceFactory: + return WorkspaceFactory( + FileRuntime(write="draft", status=UiPathRuntimeStatus.SUSPENDED), + storage=storage, + ) + + +def _uploaded(sdk: FakeSdk) -> list[bytes]: + return list(sdk.attachments.blobs.values()) + + +def test_run_uploads_the_workspace_when_a_job_suspends( + runner: CliRunner, temp_dir: str, sdk: FakeSdk, job_env: None +) -> None: + storage = MemoryStorage() + factory = _suspending_factory(storage) + + with runner.isolated_filesystem(temp_dir=temp_dir): + with ( + patch("uipath._cli.cli_run.Middlewares.next", return_value=_continue()), + patch( + "uipath._cli.cli_run.UiPathRuntimeFactoryRegistry.get", + return_value=factory, + ), + patch( + "uipath._cli.cli_run.ResourceOverwritesContext", + side_effect=_no_resource_overwrites, + ), + ): + result = runner.invoke(cli, ["run", "main", "{}"]) + + assert result.exit_code == 0, result.output + assert _uploaded(sdk) == [b"draft"] + assert (JOB_ID, *REGISTRY) in storage.values + + +@pytest.mark.parametrize("command", ["run", "debug"]) +def test_successful_conversation_exchange_uploads_the_workspace( + command: str, + runner: CliRunner, + temp_dir: str, + sdk: FakeSdk, + job_env: None, +) -> None: + factory = WorkspaceFactory(FileRuntime(write="notes"), storage=MemoryStorage()) + module = f"uipath._cli.cli_{command}" + + with runner.isolated_filesystem(temp_dir=temp_dir): + Path("uipath.json").write_text( + json.dumps( + {"fpsProperties": {"conversationalService.conversationId": "conv-1"}} + ) + ) + with ( + patch(f"{module}.Middlewares.next", return_value=_continue()), + patch(f"{module}.UiPathRuntimeFactoryRegistry.get", return_value=factory), + patch( + "uipath._cli.cli_run.ResourceOverwritesContext", + side_effect=_no_resource_overwrites, + ), + patch( + "uipath._cli.cli_debug.get_debug_bridge", + return_value=DetachedDebugBridge(), + ), + ): + result = runner.invoke(cli, [command, "main", "{}"]) + + assert result.exit_code == 0, result.output + assert _uploaded(sdk) == [b"notes"] + + +def test_run_without_a_job_leaves_the_runtime_unwrapped( + runner: CliRunner, temp_dir: str, sdk: FakeSdk, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("UIPATH_JOB_KEY", raising=False) + factory = _suspending_factory(MemoryStorage()) + + with runner.isolated_filesystem(temp_dir=temp_dir): + with ( + patch("uipath._cli.cli_run.Middlewares.next", return_value=_continue()), + patch( + "uipath._cli.cli_run.UiPathRuntimeFactoryRegistry.get", + return_value=factory, + ), + patch( + "uipath._cli.cli_run.ResourceOverwritesContext", + side_effect=_no_resource_overwrites, + ), + ): + result = runner.invoke(cli, ["run", "main", "{}"]) + + assert "Managed Workspace Unavailable" in result.output + assert _uploaded(sdk) == [] + + +def test_debug_uploads_the_workspace_when_a_job_suspends( + runner: CliRunner, temp_dir: str, sdk: FakeSdk, job_env: None +) -> None: + storage = MemoryStorage() + factory = _suspending_factory(storage) + + with runner.isolated_filesystem(temp_dir=temp_dir): + with ( + patch("uipath._cli.cli_debug.Middlewares.next", return_value=_continue()), + patch( + "uipath._cli.cli_debug.UiPathRuntimeFactoryRegistry.get", + return_value=factory, + ), + patch( + "uipath._cli.cli_debug.get_debug_bridge", + return_value=DetachedDebugBridge(), + ), + ): + result = runner.invoke(cli, ["debug", "main", "{}"]) + + assert result.exit_code == 0, result.output + assert _uploaded(sdk) == [b"draft"] + assert (JOB_ID, *REGISTRY) in storage.values diff --git a/packages/uipath/tests/cli/utils/workspace_fakes.py b/packages/uipath/tests/cli/utils/workspace_fakes.py new file mode 100644 index 000000000..27ea2a53c --- /dev/null +++ b/packages/uipath/tests/cli/utils/workspace_fakes.py @@ -0,0 +1,185 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any, AsyncGenerator +from uuid import UUID, uuid4 + +from uipath.runtime import ( + UiPathExecuteOptions, + UiPathRuntimeFactorySettings, + UiPathRuntimeResult, + UiPathRuntimeSchema, + UiPathRuntimeStatus, + UiPathStreamOptions, + get_workspace_path, +) +from uipath.runtime.events import UiPathRuntimeEvent + +OPTED_IN = UiPathRuntimeFactorySettings(managed_workspace=True) +REGISTRY = ("workspace", "attachments") + + +class FakeAttachments: + def __init__(self) -> None: + self.blobs: dict[UUID, bytes] = {} + self.folder_keys: list[str | None] = [] + + async def upload_async( + self, + *, + name: str, + content: str | bytes | None = None, + source_path: str | None = None, + folder_key: str | None = None, + folder_path: str | None = None, + ) -> UUID: + self.folder_keys.append(folder_key) + key = uuid4() + if source_path is not None: + self.blobs[key] = Path(source_path).read_bytes() + elif isinstance(content, str): + self.blobs[key] = content.encode() + else: + self.blobs[key] = content or b"" + return key + + async def download_async( + self, + *, + key: UUID, + destination_path: str, + folder_key: str | None = None, + folder_path: str | None = None, + ) -> str: + self.folder_keys.append(folder_key) + Path(destination_path).write_bytes(self.blobs[key]) + return destination_path + + +class FakeJobs: + def __init__(self) -> None: + self.links: list[tuple[UUID, UUID]] = [] + self.folder_keys: list[str | None] = [] + + async def list_attachments_async( + self, + *, + job_key: UUID, + folder_key: str | None = None, + folder_path: str | None = None, + ) -> list[str]: + self.folder_keys.append(folder_key) + return [str(attachment) for job, attachment in self.links if job == job_key] + + async def link_attachment_async( + self, + *, + job_key: UUID, + attachment_key: UUID, + folder_key: str | None = None, + folder_path: str | None = None, + ) -> None: + self.folder_keys.append(folder_key) + self.links.append((job_key, attachment_key)) + + +class FakeSdk: + """Stands in for ``UiPath()``: the attachment and job APIs are the network boundary.""" + + def __init__(self) -> None: + self.attachments = FakeAttachments() + self.jobs = FakeJobs() + + +class MemoryStorage: + def __init__(self) -> None: + self.values: dict[tuple[str, str, str], Any] = {} + + async def set_value( + self, runtime_id: str, namespace: str, key: str, value: Any + ) -> None: + self.values[(runtime_id, namespace, key)] = value + + async def get_value(self, runtime_id: str, namespace: str, key: str) -> Any: + return self.values.get((runtime_id, namespace, key)) + + +class FileRuntime: + """Writes or reads one workspace file, the way an agent's file tools would.""" + + def __init__( + self, + *, + write: str | None = None, + status: UiPathRuntimeStatus = UiPathRuntimeStatus.SUCCESSFUL, + ) -> None: + self.write = write + self.status = status + self.workspace_path: Path | None = None + + async def execute( + self, + input: dict[str, Any] | None = None, + options: UiPathExecuteOptions | None = None, + ) -> UiPathRuntimeResult: + self.workspace_path = get_workspace_path() + report = self.workspace_path / "report.md" + if self.write is not None: + report.write_text(self.write) + content = report.read_text() if report.exists() else None + return UiPathRuntimeResult(status=self.status, output={"report": content}) + + async def stream( + self, + input: dict[str, Any] | None = None, + options: UiPathStreamOptions | None = None, + ) -> AsyncGenerator[UiPathRuntimeEvent, None]: + yield await self.execute(input, options) + + async def get_schema(self) -> UiPathRuntimeSchema: + return UiPathRuntimeSchema( + filePath="main", + uniqueId="main", + type="agent", + input={"type": "object", "properties": {}}, + output={"type": "object", "properties": {}}, + ) + + async def dispose(self) -> None: + pass + + +class WorkspaceFactory: + """A factory that opts in to the managed workspace and hands out ``FileRuntime``s.""" + + def __init__( + self, + runtime: FileRuntime, + *, + storage: MemoryStorage | None, + settings: UiPathRuntimeFactorySettings | None = OPTED_IN, + ) -> None: + self.runtime = runtime + self.storage = storage + self.settings = settings + self.runtime_ids: list[str] = [] + self.settings_reads = 0 + + def discover_entrypoints(self) -> list[str]: + return ["main"] + + async def get_settings(self) -> UiPathRuntimeFactorySettings | None: + self.settings_reads += 1 + return self.settings + + async def get_storage(self) -> MemoryStorage | None: + return self.storage + + async def new_runtime( + self, entrypoint: str, runtime_id: str, **kwargs: Any + ) -> FileRuntime: + self.runtime_ids.append(runtime_id) + return self.runtime + + async def dispose(self) -> None: + pass From 46d69592bcc977843f4033aa5a9fd6438f300089 Mon Sep 17 00:00:00 2001 From: tudormatei Date: Thu, 5 Nov 2026 11:16:15 +0200 Subject: [PATCH 2/4] test(cli): drop workspace tests covered at another layer The resume round trip, the conversation policy and folder removal are already checked by the run/debug command tests or by uipath-runtime's ManagedWorkspace tests. The settings-read count only pinned an optimization. Co-Authored-By: Claude Opus 5.5 --- .../test_eval_runtime_managed_workspace.py | 10 ---- .../tests/cli/test_managed_workspace.py | 47 ++----------------- .../uipath/tests/cli/utils/workspace_fakes.py | 4 -- 3 files changed, 3 insertions(+), 58 deletions(-) diff --git a/packages/uipath/tests/cli/eval/test_eval_runtime_managed_workspace.py b/packages/uipath/tests/cli/eval/test_eval_runtime_managed_workspace.py index e2820cfc8..9a055b978 100644 --- a/packages/uipath/tests/cli/eval/test_eval_runtime_managed_workspace.py +++ b/packages/uipath/tests/cli/eval/test_eval_runtime_managed_workspace.py @@ -64,16 +64,6 @@ async def test_eval_uploads_each_suspended_item_workspace(sdk: FakeSdk) -> None: assert {key[0] for key in storage.values if key[1:] == REGISTRY} == set(item_ids) -async def test_eval_reads_factory_settings_once_for_all_items(sdk: FakeSdk) -> None: - factory = _suspending_factory(MemoryStorage()) - - await evaluate( - factory, UiPathTraceManager(), await _eval_context(items=2), EventBus() - ) - - assert factory.settings_reads == 1 - - async def test_eval_set_run_carries_the_factory_agent_type(sdk: FakeSdk) -> None: created: list[Any] = [] event_bus = EventBus() diff --git a/packages/uipath/tests/cli/test_managed_workspace.py b/packages/uipath/tests/cli/test_managed_workspace.py index fd6c9adbd..2330c11d9 100644 --- a/packages/uipath/tests/cli/test_managed_workspace.py +++ b/packages/uipath/tests/cli/test_managed_workspace.py @@ -22,21 +22,13 @@ JOB_ID = str(uuid4()) -async def _run( - runtime: FileRuntime, - storage: MemoryStorage | None, - *, - settings: UiPathRuntimeFactorySettings | None = OPTED_IN, - job_id: str | None = JOB_ID, - conversation_id: str | None = None, -) -> UiPathRuntimeResult: +async def _run(runtime: FileRuntime, storage: MemoryStorage) -> UiPathRuntimeResult: wrapped = await wrap_with_managed_workspace( runtime, factory=WorkspaceFactory(runtime, storage=storage), - settings=settings, + settings=OPTED_IN, runtime_id="runtime-1", - job_id=job_id, - conversation_id=conversation_id, + job_id=JOB_ID, ) try: return await wrapped.execute() @@ -44,19 +36,6 @@ async def _run( await wrapped.dispose() -async def test_files_written_before_a_suspend_are_back_after_resume( - sdk: FakeSdk, -) -> None: - storage = MemoryStorage() - - await _run( - FileRuntime(write="draft", status=UiPathRuntimeStatus.SUSPENDED), storage - ) - resumed = await _run(FileRuntime(), storage) - - assert resumed.output == {"report": "draft"} - - async def test_uploads_are_linked_to_the_job(sdk: FakeSdk) -> None: await _run( FileRuntime(write="draft", status=UiPathRuntimeStatus.SUSPENDED), @@ -91,26 +70,6 @@ async def test_successful_run_outside_a_conversation_uploads_nothing( assert sdk.attachments.blobs == {} -async def test_successful_exchange_in_a_conversation_keeps_files_for_the_next( - sdk: FakeSdk, -) -> None: - storage = MemoryStorage() - - await _run(FileRuntime(write="notes"), storage, conversation_id="conv-1") - next_exchange = await _run(FileRuntime(), storage, conversation_id="conv-1") - - assert next_exchange.output == {"report": "notes"} - - -async def test_dispose_removes_the_workspace_folder(sdk: FakeSdk) -> None: - runtime = FileRuntime(write="draft", status=UiPathRuntimeStatus.SUSPENDED) - - await _run(runtime, MemoryStorage()) - - assert runtime.workspace_path is not None - assert not runtime.workspace_path.exists() - - @pytest.mark.parametrize( ("settings", "job_id", "storage"), [ diff --git a/packages/uipath/tests/cli/utils/workspace_fakes.py b/packages/uipath/tests/cli/utils/workspace_fakes.py index 27ea2a53c..bdf02a70a 100644 --- a/packages/uipath/tests/cli/utils/workspace_fakes.py +++ b/packages/uipath/tests/cli/utils/workspace_fakes.py @@ -162,14 +162,11 @@ def __init__( self.runtime = runtime self.storage = storage self.settings = settings - self.runtime_ids: list[str] = [] - self.settings_reads = 0 def discover_entrypoints(self) -> list[str]: return ["main"] async def get_settings(self) -> UiPathRuntimeFactorySettings | None: - self.settings_reads += 1 return self.settings async def get_storage(self) -> MemoryStorage | None: @@ -178,7 +175,6 @@ async def get_storage(self) -> MemoryStorage | None: async def new_runtime( self, entrypoint: str, runtime_id: str, **kwargs: Any ) -> FileRuntime: - self.runtime_ids.append(runtime_id) return self.runtime async def dispose(self) -> None: From 56e9b80d9ec51145b3b89bf392a44cbc92a0df09 Mon Sep 17 00:00:00 2001 From: tudormatei Date: Thu, 3 Dec 2026 13:10:46 +0200 Subject: [PATCH 3/4] chore(uipath): require uipath-runtime 0.13.8 ManagedWorkspace first ships in uipath-runtime 0.13.8; 0.13.7 was released without it, so run, debug and eval would fail at import. The lock is regenerated once 0.13.8 is on PyPI. Co-Authored-By: Claude Opus 5.5 --- packages/uipath/pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/uipath/pyproject.toml b/packages/uipath/pyproject.toml index dae9eebae..6bc445d86 100644 --- a/packages/uipath/pyproject.toml +++ b/packages/uipath/pyproject.toml @@ -1,12 +1,12 @@ [project] name = "uipath" -version = "2.15.15" +version = "2.15.16" description = "Python SDK and CLI for UiPath Platform, enabling programmatic interaction with automation services, process management, and deployment tools." readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" dependencies = [ "uipath-core>=0.5.35, <0.6.0", - "uipath-runtime>=0.13.7, <0.14.0", + "uipath-runtime>=0.13.8, <0.14.0", "uipath-platform>=0.3.20, <0.4.0", "uipath-ipc>=2.5.1, <2.6.0", "click>=8.3.3, <9.0.0", From 7ae4f93d511e8c4d77408f4dc30208961706a9b2 Mon Sep 17 00:00:00 2001 From: tudormatei Date: Thu, 3 Dec 2026 13:21:32 +0200 Subject: [PATCH 4/4] test(cli): check that a resumed run gets its files back The folder-key test discarded the resumed run's output, so it passed even when nothing was restored: the first run's upload and link calls already filled both folder-key lists. With restore turned off, every uipath test still passed. It now asserts the resumed run reads the file, which also makes sure the download used the job folder. Co-Authored-By: Claude Opus 5.5 --- packages/uipath/tests/cli/test_managed_workspace.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/uipath/tests/cli/test_managed_workspace.py b/packages/uipath/tests/cli/test_managed_workspace.py index 2330c11d9..0033cbddb 100644 --- a/packages/uipath/tests/cli/test_managed_workspace.py +++ b/packages/uipath/tests/cli/test_managed_workspace.py @@ -46,7 +46,7 @@ async def test_uploads_are_linked_to_the_job(sdk: FakeSdk) -> None: assert list(sdk.attachments.blobs.values()) == [b"draft"] -async def test_attachment_calls_use_the_job_folder( +async def test_resumed_run_gets_its_files_back_from_the_job_folder( sdk: FakeSdk, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setenv(ENV_FOLDER_KEY, "folder-1") @@ -55,8 +55,9 @@ async def test_attachment_calls_use_the_job_folder( await _run( FileRuntime(write="draft", status=UiPathRuntimeStatus.SUSPENDED), storage ) - await _run(FileRuntime(), storage) + resumed = await _run(FileRuntime(), storage) + assert resumed.output == {"report": "draft"} assert sdk.attachments.folder_keys assert sdk.jobs.folder_keys assert set(sdk.attachments.folder_keys + sdk.jobs.folder_keys) == {"folder-1"}