Skip to content

Commit 5c530ce

Browse files
openhands-agentadityasoni9998
authored andcommitted
Fix issue All-Hands-AI#6531: [Bug]: GITHUB_TOKEN would missing when the runtime resume (All-Hands-AI#6533)
1 parent 887a4bf commit 5c530ce

File tree

3 files changed

+71
-1
lines changed

3 files changed

+71
-1
lines changed

openhands/runtime/base.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,11 +172,14 @@ def add_env_vars(self, env_vars: dict[str, str]) -> None:
172172
# Note: we don't log the vars values, they're leaking info
173173
logger.debug('Added env vars to IPython')
174174

175-
# Add env vars to the Bash shell
175+
# Add env vars to the Bash shell and .bashrc for persistence
176176
cmd = ''
177+
bashrc_cmd = ''
177178
for key, value in env_vars.items():
178179
# Note: json.dumps gives us nice escaping for free
179180
cmd += f'export {key}={json.dumps(value)}; '
181+
# Add to .bashrc if not already present
182+
bashrc_cmd += f'grep -q "^export {key}=" ~/.bashrc || echo "export {key}={json.dumps(value)}" >> ~/.bashrc; '
180183
if not cmd:
181184
return
182185
cmd = cmd.strip()
@@ -190,6 +193,15 @@ def add_env_vars(self, env_vars: dict[str, str]) -> None:
190193
f'Failed to add env vars [{env_vars.keys()}] to environment: {obs.content}'
191194
)
192195

196+
# Add to .bashrc for persistence
197+
bashrc_cmd = bashrc_cmd.strip()
198+
logger.debug(f'Adding env var to .bashrc: {env_vars.keys()}')
199+
obs = self.run(CmdRunAction(bashrc_cmd))
200+
if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0:
201+
raise RuntimeError(
202+
f'Failed to add env vars [{env_vars.keys()}] to .bashrc: {obs.content}'
203+
)
204+
193205
def on_event(self, event: Event) -> None:
194206
if isinstance(event, Action):
195207
asyncio.get_event_loop().run_until_complete(self._handle_action(event))

openhands/runtime/impl/docker/docker_runtime.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,32 @@ def web_hosts(self):
401401

402402
return hosts
403403

404+
def pause(self):
405+
"""Pause the runtime by stopping the container.
406+
This is different from container.stop() as it ensures environment variables are properly preserved."""
407+
if not self.container:
408+
raise RuntimeError("Container not initialized")
409+
410+
# First, ensure all environment variables are properly persisted in .bashrc
411+
# This is already handled by add_env_vars in base.py
412+
413+
# Stop the container
414+
self.container.stop()
415+
self.log('debug', f'Container {self.container_name} paused')
416+
417+
def resume(self):
418+
"""Resume the runtime by starting the container.
419+
This is different from container.start() as it ensures environment variables are properly restored."""
420+
if not self.container:
421+
raise RuntimeError("Container not initialized")
422+
423+
# Start the container
424+
self.container.start()
425+
self.log('debug', f'Container {self.container_name} resumed')
426+
427+
# Wait for the container to be ready
428+
self._wait_until_alive()
429+
404430
@classmethod
405431
async def delete(cls, conversation_id: str):
406432
docker_client = cls._init_docker_client()

tests/runtime/test_env_vars.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,35 @@ def test_env_vars_added_by_config(temp_dir, runtime_cls):
8181
and obs.content.strip().split('\r\n')[0].strip() == 'added_value'
8282
)
8383
_close_test_runtime(runtime)
84+
85+
86+
def test_docker_runtime_env_vars_persist_after_restart(temp_dir):
87+
from openhands.runtime.impl.docker.docker_runtime import DockerRuntime
88+
89+
runtime = _load_runtime(temp_dir, DockerRuntime)
90+
91+
# Add a test environment variable
92+
runtime.add_env_vars({'GITHUB_TOKEN': 'test_token'})
93+
94+
# Verify the variable is set in current session
95+
obs = runtime.run_action(CmdRunAction(command='echo $GITHUB_TOKEN'))
96+
assert obs.exit_code == 0
97+
assert obs.content.strip().split('\r\n')[0].strip() == 'test_token'
98+
99+
# Verify the variable is added to .bashrc
100+
obs = runtime.run_action(
101+
CmdRunAction(command='grep "^export GITHUB_TOKEN=" ~/.bashrc')
102+
)
103+
assert obs.exit_code == 0
104+
assert 'export GITHUB_TOKEN=' in obs.content
105+
106+
# Test pause/resume cycle
107+
runtime.pause()
108+
runtime.resume()
109+
110+
# Verify the variable persists after restart
111+
obs = runtime.run_action(CmdRunAction(command='echo $GITHUB_TOKEN'))
112+
assert obs.exit_code == 0
113+
assert obs.content.strip().split('\r\n')[0].strip() == 'test_token'
114+
115+
_close_test_runtime(runtime)

0 commit comments

Comments
 (0)