diff --git a/openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py b/openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py index 067674a6838..9715ceae600 100644 --- a/openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py +++ b/openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py @@ -18,7 +18,7 @@ from openhands.sdk.conversation.cancellation import CancellationToken from openhands.sdk.conversation.event_store import EventLog from openhands.sdk.conversation.exceptions import ConversationRunError -from openhands.sdk.conversation.secret_registry import SecretValue +from openhands.sdk.conversation.secret_registry import SecretRegistry, SecretValue from openhands.sdk.conversation.state import ( ConversationExecutionStatus, ConversationState, @@ -909,6 +909,7 @@ def fork( stuck_detection=self._stuck_detector is not None, visualizer=type(self._visualizer) if self._visualizer else None, delete_on_close=self.delete_on_close, + cipher=self._cipher, tags=tags, _parent_llm_call_context=self._llm_call_context, ) @@ -948,6 +949,14 @@ def fork( ) fork_conv._state.agent_state = copy.deepcopy(self._state.agent_state) + # Runtime-added secrets (update_secrets) live only in the source's + # registry; __init__ re-seeded only agent_context/request secrets. + # Reassigning the public field triggers the autosave, so the fork's + # base_state.json persists them encrypted with its cipher. + fork_conv._state.secret_registry = SecretRegistry( + secret_sources=dict(self._state.secret_registry.secret_sources) + ) + # Reset or copy metrics if not reset_metrics: fork_conv._state.stats = self._state.stats.model_copy(deep=True) diff --git a/tests/agent_server/test_conversation_service.py b/tests/agent_server/test_conversation_service.py index 285c3e6bf19..64ff21ed489 100644 --- a/tests/agent_server/test_conversation_service.py +++ b/tests/agent_server/test_conversation_service.py @@ -4148,6 +4148,50 @@ async def test_fork_unknown_event_raises_without_leaking_dir(self, tmp_path): # Validation must fail-fast before any fork dir is written to disk. assert {p.name for p in conversations_dir.iterdir()} == before + @pytest.mark.asyncio + async def test_cipher_backed_fork_resumes_with_credentials(self, tmp_path): + """A cipher-backed fork survives a restart with its secrets (#5465).""" + conversations_dir = tmp_path / "conversations" + cipher = Cipher("fork-resume-test-key") + request = StartConversationRequest( + agent=Agent( + llm=LLM( + model="gpt-4o", + api_key=SecretStr("sk-fork-test"), + usage_id="test-llm", + ), + tools=[], + ), + workspace=LocalWorkspace(working_dir=tmp_path / "workspace"), + ) + + async with ConversationService( + conversations_dir=conversations_dir, cipher=cipher + ) as svc: + info, _ = await svc.start_conversation(request) + source_service = await svc.get_event_service(info.id) + assert source_service is not None + source_service.get_conversation().update_secrets({"MY_TOKEN": "tok-123"}) + + fork_info = await svc.fork_conversation(info.id) + assert fork_info is not None + + async with ConversationService( + conversations_dir=conversations_dir, cipher=cipher + ) as restarted: + # Resume path: the restarted server loads the fork from its + # persisted base_state.json with agent=None. + fork_service = await restarted.get_event_service(fork_info.id) + assert fork_service is not None + fork_conversation = fork_service.get_conversation() + api_key = fork_conversation.agent.llm.api_key + assert isinstance(api_key, SecretStr) + assert api_key.get_secret_value() == "sk-fork-test" + assert ( + fork_conversation.state.secret_registry.get_secret_value("MY_TOKEN") + == "tok-123" + ) + @pytest.mark.asyncio @pytest.mark.parametrize( "navigate_to_none", [False, True], ids=["to_event", "to_empty_tree"] diff --git a/tests/sdk/conversation/local/test_fork.py b/tests/sdk/conversation/local/test_fork.py index b9b93141cda..05186364771 100644 --- a/tests/sdk/conversation/local/test_fork.py +++ b/tests/sdk/conversation/local/test_fork.py @@ -1,5 +1,6 @@ """Tests for Conversation.fork() primitive.""" +import json import tempfile import threading import uuid @@ -16,6 +17,7 @@ from openhands.sdk.event.llm_convertible import MessageEvent, SystemPromptEvent from openhands.sdk.llm import LLM, Message, TextContent from openhands.sdk.tool import Action, Observation, ToolDefinition, ToolExecutor +from openhands.sdk.utils.cipher import Cipher def _agent() -> Agent: @@ -349,3 +351,55 @@ def test_fork_with_aliased_agent_does_not_clobber_source_cache_key(): ) assert fork.get_llm_call_context().prompt_cache_key == str(fork.id) assert fork.agent.llm is not src.agent.llm + + +def test_fork_inherits_cipher_for_secret_encryption(): + """Forked conversation keeps encrypting secrets at rest (#5465). + + The fork resumes from its own base_state.json. If ``fork()`` dropped the + source cipher, the fork's LLM api_key would serialize redacted + (``**********``) instead of encrypted, and its first resumed turn would + fail with LLMAuthenticationError. + """ + with tempfile.TemporaryDirectory() as tmpdir: + cipher = Cipher(secret_key="fork-cipher-key") + src = LocalConversation( + agent=_agent(), + workspace=tmpdir, + persistence_dir=tmpdir, + cipher=cipher, + ) + + fork = src.fork() + + # The fork's persisted base_state keeps the key encrypted with the + # source's cipher; decrypting it recovers the original credential. + base_path = Path(tmpdir) / fork.id.hex / "base_state.json" + base = json.loads(base_path.read_text()) + api_key = base["agent"]["llm"]["api_key"] + assert api_key != "**********" + assert cipher.try_decrypt_str(api_key) == "test-key" + + +def test_fork_keeps_runtime_added_secrets(): + """A fork inherits secrets added via update_secrets() after creation.""" + with tempfile.TemporaryDirectory() as tmpdir: + cipher = Cipher(secret_key="fork-cipher-key") + src = LocalConversation( + agent=_agent(), + workspace=tmpdir, + persistence_dir=tmpdir, + cipher=cipher, + ) + src.update_secrets({"MY_TOKEN": "tok-123"}) + + fork = src.fork() + + assert fork.state.secret_registry.get_secret_value("MY_TOKEN") == "tok-123" + # The runtime secret also persists encrypted in the fork's + # base_state, so a resume keeps it. + base_path = Path(tmpdir) / fork.id.hex / "base_state.json" + base = json.loads(base_path.read_text()) + token = base["secret_registry"]["secret_sources"]["MY_TOKEN"]["value"] + assert token != "**********" + assert cipher.try_decrypt_str(token) == "tok-123"