test_runtime.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  1. """Test the EventStreamRuntime, which connects to the RuntimeClient running in the sandbox."""
  2. import asyncio
  3. import json
  4. import os
  5. import tempfile
  6. import time
  7. from unittest.mock import patch
  8. import pytest
  9. from pytest import TempPathFactory
  10. from opendevin.core.config import AppConfig, SandboxConfig, load_from_env
  11. from opendevin.core.logger import opendevin_logger as logger
  12. from opendevin.events import EventStream
  13. from opendevin.events.action import (
  14. BrowseInteractiveAction,
  15. BrowseURLAction,
  16. CmdRunAction,
  17. FileReadAction,
  18. FileWriteAction,
  19. IPythonRunCellAction,
  20. )
  21. from opendevin.events.observation import (
  22. BrowserOutputObservation,
  23. CmdOutputObservation,
  24. ErrorObservation,
  25. FileReadObservation,
  26. FileWriteObservation,
  27. IPythonRunCellObservation,
  28. )
  29. from opendevin.runtime.client.runtime import EventStreamRuntime
  30. from opendevin.runtime.plugins import AgentSkillsRequirement, JupyterRequirement
  31. from opendevin.runtime.runtime import Runtime
  32. from opendevin.storage import get_file_store
  33. @pytest.fixture(autouse=True)
  34. def print_method_name(request):
  35. print('\n########################################################################')
  36. print(f'Running test: {request.node.name}')
  37. print('########################################################################')
  38. yield
  39. @pytest.fixture
  40. def temp_dir(tmp_path_factory: TempPathFactory) -> str:
  41. return str(tmp_path_factory.mktemp('test_runtime'))
  42. TEST_RUNTIME = os.getenv('TEST_RUNTIME', 'both')
  43. PY3_FOR_TESTING = '/opendevin/miniforge3/bin/mamba run -n base python3'
  44. # Depending on TEST_RUNTIME, feed the appropriate box class(es) to the test.
  45. def get_box_classes():
  46. runtime = TEST_RUNTIME
  47. if runtime.lower() == 'eventstream':
  48. return [EventStreamRuntime]
  49. else:
  50. return [EventStreamRuntime]
  51. # This assures that all tests run together per runtime, not alternating between them,
  52. # which cause errors (especially outside GitHub actions).
  53. @pytest.fixture(scope='module', params=get_box_classes())
  54. def box_class(request):
  55. time.sleep(2)
  56. return request.param
  57. # TODO: We will change this to `run_as_user` when `ServerRuntime` is deprecated.
  58. # since `EventStreamRuntime` supports running as an arbitrary user.
  59. @pytest.fixture(scope='module', params=[True, False])
  60. def run_as_devin(request):
  61. time.sleep(1)
  62. return request.param
  63. @pytest.fixture(scope='module', params=[True, False])
  64. def enable_auto_lint(request):
  65. time.sleep(1)
  66. return request.param
  67. @pytest.fixture(
  68. scope='module', params=['nikolaik/python-nodejs:python3.11-nodejs22', 'debian:11']
  69. )
  70. def container_image(request):
  71. time.sleep(1)
  72. return request.param
  73. async def _load_runtime(
  74. temp_dir,
  75. box_class,
  76. run_as_devin: bool = True,
  77. enable_auto_lint: bool = False,
  78. container_image: str | None = None,
  79. browsergym_eval_env: str | None = None,
  80. ) -> Runtime:
  81. sid = 'test'
  82. cli_session = 'main_test'
  83. # AgentSkills need to be initialized **before** Jupyter
  84. # otherwise Jupyter will not access the proper dependencies installed by AgentSkills
  85. plugins = [AgentSkillsRequirement(), JupyterRequirement()]
  86. config = AppConfig(
  87. workspace_base=temp_dir,
  88. workspace_mount_path=temp_dir,
  89. sandbox=SandboxConfig(
  90. use_host_network=True,
  91. browsergym_eval_env=browsergym_eval_env,
  92. ),
  93. )
  94. load_from_env(config, os.environ)
  95. config.run_as_devin = run_as_devin
  96. config.sandbox.enable_auto_lint = enable_auto_lint
  97. file_store = get_file_store(config.file_store, config.file_store_path)
  98. event_stream = EventStream(cli_session, file_store)
  99. if container_image is not None:
  100. config.sandbox.container_image = container_image
  101. if box_class == EventStreamRuntime:
  102. # NOTE: we will use the default container image specified in the config.sandbox
  103. # if it is an official od_runtime image.
  104. cur_container_image = config.sandbox.container_image
  105. if 'od_runtime' not in cur_container_image and cur_container_image not in {
  106. 'xingyaoww/od-eval-miniwob:v1.0'
  107. }: # a special exception list
  108. cur_container_image = 'nikolaik/python-nodejs:python3.11-nodejs22'
  109. logger.warning(
  110. f'`{config.sandbox.container_image}` is not an od_runtime image. Will use `{cur_container_image}` as the container image for testing.'
  111. )
  112. runtime = EventStreamRuntime(
  113. config=config,
  114. event_stream=event_stream,
  115. sid=sid,
  116. plugins=plugins,
  117. # NOTE: we probably don't have a default container image `/sandbox` for the event stream runtime
  118. # Instead, we will pre-build a suite of container images with OD-runtime-cli installed.
  119. container_image=cur_container_image,
  120. )
  121. await runtime.ainit()
  122. else:
  123. raise ValueError(f'Invalid box class: {box_class}')
  124. await asyncio.sleep(1)
  125. return runtime
  126. @pytest.mark.asyncio
  127. async def test_env_vars_os_environ(temp_dir, box_class, run_as_devin):
  128. with patch.dict(os.environ, {'SANDBOX_ENV_FOOBAR': 'BAZ'}):
  129. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  130. obs: CmdOutputObservation = await runtime.run_action(
  131. CmdRunAction(command='env')
  132. )
  133. print(obs)
  134. obs: CmdOutputObservation = await runtime.run_action(
  135. CmdRunAction(command='echo $FOOBAR')
  136. )
  137. print(obs)
  138. assert obs.exit_code == 0, 'The exit code should be 0.'
  139. assert (
  140. obs.content.strip().split('\n\r')[0].strip() == 'BAZ'
  141. ), f'Output: [{obs.content}] for {box_class}'
  142. await runtime.close()
  143. await asyncio.sleep(1)
  144. @pytest.mark.asyncio
  145. async def test_env_vars_runtime_add_env_vars(temp_dir, box_class):
  146. runtime = await _load_runtime(temp_dir, box_class)
  147. await runtime.add_env_vars({'QUUX': 'abc"def'})
  148. obs: CmdOutputObservation = await runtime.run_action(
  149. CmdRunAction(command='echo $QUUX')
  150. )
  151. print(obs)
  152. assert obs.exit_code == 0, 'The exit code should be 0.'
  153. assert (
  154. obs.content.strip().split('\r\n')[0].strip() == 'abc"def'
  155. ), f'Output: [{obs.content}] for {box_class}'
  156. await runtime.close()
  157. await asyncio.sleep(1)
  158. @pytest.mark.asyncio
  159. async def test_env_vars_runtime_add_empty_dict(temp_dir, box_class):
  160. runtime = await _load_runtime(temp_dir, box_class)
  161. prev_obs = await runtime.run_action(CmdRunAction(command='env'))
  162. assert prev_obs.exit_code == 0, 'The exit code should be 0.'
  163. print(prev_obs)
  164. await runtime.add_env_vars({})
  165. obs = await runtime.run_action(CmdRunAction(command='env'))
  166. assert obs.exit_code == 0, 'The exit code should be 0.'
  167. print(obs)
  168. assert (
  169. obs.content == prev_obs.content
  170. ), 'The env var content should be the same after adding an empty dict.'
  171. await runtime.close()
  172. await asyncio.sleep(1)
  173. @pytest.mark.asyncio
  174. async def test_env_vars_runtime_add_multiple_env_vars(temp_dir, box_class):
  175. runtime = await _load_runtime(temp_dir, box_class)
  176. await runtime.add_env_vars({'QUUX': 'abc"def', 'FOOBAR': 'xyz'})
  177. obs: CmdOutputObservation = await runtime.run_action(
  178. CmdRunAction(command='echo $QUUX $FOOBAR')
  179. )
  180. print(obs)
  181. assert obs.exit_code == 0, 'The exit code should be 0.'
  182. assert (
  183. obs.content.strip().split('\r\n')[0].strip() == 'abc"def xyz'
  184. ), f'Output: [{obs.content}] for {box_class}'
  185. await runtime.close()
  186. await asyncio.sleep(1)
  187. @pytest.mark.asyncio
  188. async def test_env_vars_runtime_add_env_vars_overwrite(temp_dir, box_class):
  189. with patch.dict(os.environ, {'SANDBOX_ENV_FOOBAR': 'BAZ'}):
  190. runtime = await _load_runtime(temp_dir, box_class)
  191. await runtime.add_env_vars({'FOOBAR': 'xyz'})
  192. obs: CmdOutputObservation = await runtime.run_action(
  193. CmdRunAction(command='echo $FOOBAR')
  194. )
  195. print(obs)
  196. assert obs.exit_code == 0, 'The exit code should be 0.'
  197. assert (
  198. obs.content.strip().split('\r\n')[0].strip() == 'xyz'
  199. ), f'Output: [{obs.content}] for {box_class}'
  200. await runtime.close()
  201. await asyncio.sleep(1)
  202. @pytest.mark.asyncio
  203. async def test_bash_command_pexcept(temp_dir, box_class, run_as_devin):
  204. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  205. # We set env var PS1="\u@\h:\w $"
  206. # and construct the PEXCEPT prompt base on it.
  207. # When run `env`, bad implementation of CmdRunAction will be pexcepted by this
  208. # and failed to pexcept the right content, causing it fail to get error code.
  209. obs = await runtime.run_action(CmdRunAction(command='env'))
  210. # For example:
  211. # 02:16:13 - opendevin:DEBUG: client.py:78 - Executing command: env
  212. # 02:16:13 - opendevin:DEBUG: client.py:82 - Command output: PYTHONUNBUFFERED=1
  213. # CONDA_EXE=/opendevin/miniforge3/bin/conda
  214. # [...]
  215. # LC_CTYPE=C.UTF-8
  216. # PS1=\u@\h:\w $
  217. # 02:16:13 - opendevin:DEBUG: client.py:89 - Executing command for exit code: env
  218. # 02:16:13 - opendevin:DEBUG: client.py:92 - Exit code Output:
  219. # CONDA_DEFAULT_ENV=base
  220. # As long as the exit code is 0, the test will pass.
  221. assert isinstance(
  222. obs, CmdOutputObservation
  223. ), 'The observation should be a CmdOutputObservation.'
  224. assert obs.exit_code == 0, 'The exit code should be 0.'
  225. await runtime.close()
  226. await asyncio.sleep(1)
  227. @pytest.mark.asyncio
  228. async def test_simple_cmd_ipython_and_fileop(temp_dir, box_class, run_as_devin):
  229. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  230. # Test run command
  231. action_cmd = CmdRunAction(command='ls -l')
  232. logger.info(action_cmd, extra={'msg_type': 'ACTION'})
  233. obs = await runtime.run_action(action_cmd)
  234. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  235. assert isinstance(obs, CmdOutputObservation)
  236. assert obs.exit_code == 0
  237. assert 'total 0' in obs.content
  238. # Test run ipython
  239. test_code = "print('Hello, `World`!\\n')"
  240. action_ipython = IPythonRunCellAction(code=test_code)
  241. logger.info(action_ipython, extra={'msg_type': 'ACTION'})
  242. obs = await runtime.run_action(action_ipython)
  243. assert isinstance(obs, IPythonRunCellObservation)
  244. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  245. assert obs.content.strip() == 'Hello, `World`!'
  246. # Test read file (file should not exist)
  247. action_read = FileReadAction(path='hello.sh')
  248. logger.info(action_read, extra={'msg_type': 'ACTION'})
  249. obs = await runtime.run_action(action_read)
  250. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  251. assert isinstance(obs, ErrorObservation)
  252. assert 'File not found' in obs.content
  253. # Test write file
  254. action_write = FileWriteAction(content='echo "Hello, World!"', path='hello.sh')
  255. logger.info(action_write, extra={'msg_type': 'ACTION'})
  256. obs = await runtime.run_action(action_write)
  257. assert isinstance(obs, FileWriteObservation)
  258. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  259. assert obs.content == ''
  260. # event stream runtime will always use absolute path
  261. assert obs.path == '/workspace/hello.sh'
  262. # Test read file (file should exist)
  263. action_read = FileReadAction(path='hello.sh')
  264. logger.info(action_read, extra={'msg_type': 'ACTION'})
  265. obs = await runtime.run_action(action_read)
  266. assert isinstance(
  267. obs, FileReadObservation
  268. ), 'The observation should be a FileReadObservation.'
  269. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  270. assert obs.content == 'echo "Hello, World!"\n'
  271. assert obs.path == '/workspace/hello.sh'
  272. # clean up
  273. action = CmdRunAction(command='rm -rf hello.sh')
  274. logger.info(action, extra={'msg_type': 'ACTION'})
  275. obs = await runtime.run_action(action)
  276. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  277. assert obs.exit_code == 0
  278. await runtime.close()
  279. await asyncio.sleep(1)
  280. @pytest.mark.asyncio
  281. async def test_simple_browse(temp_dir, box_class, run_as_devin):
  282. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  283. # Test browse
  284. action_cmd = CmdRunAction(
  285. command=f'{PY3_FOR_TESTING} -m http.server 8000 > server.log 2>&1 &'
  286. )
  287. logger.info(action_cmd, extra={'msg_type': 'ACTION'})
  288. obs = await runtime.run_action(action_cmd)
  289. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  290. assert isinstance(obs, CmdOutputObservation)
  291. assert obs.exit_code == 0
  292. assert '[1]' in obs.content
  293. action_cmd = CmdRunAction(command='sleep 5 && cat server.log')
  294. logger.info(action_cmd, extra={'msg_type': 'ACTION'})
  295. obs = await runtime.run_action(action_cmd)
  296. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  297. assert obs.exit_code == 0
  298. action_browse = BrowseURLAction(url='http://localhost:8000')
  299. logger.info(action_browse, extra={'msg_type': 'ACTION'})
  300. obs = await runtime.run_action(action_browse)
  301. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  302. assert isinstance(obs, BrowserOutputObservation)
  303. assert 'http://localhost:8000' in obs.url
  304. assert not obs.error
  305. assert obs.open_pages_urls == ['http://localhost:8000/']
  306. assert obs.active_page_index == 0
  307. assert obs.last_browser_action == 'goto("http://localhost:8000")'
  308. assert obs.last_browser_action_error == ''
  309. assert 'Directory listing for /' in obs.content
  310. assert 'server.log' in obs.content
  311. # clean up
  312. action = CmdRunAction(command='rm -rf server.log')
  313. logger.info(action, extra={'msg_type': 'ACTION'})
  314. obs = await runtime.run_action(action)
  315. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  316. assert obs.exit_code == 0
  317. await runtime.close()
  318. await asyncio.sleep(1)
  319. @pytest.mark.asyncio
  320. async def test_browsergym_eval_env(temp_dir):
  321. runtime = await _load_runtime(
  322. temp_dir,
  323. # only supported in event stream runtime
  324. box_class=EventStreamRuntime,
  325. run_as_devin=False, # need root permission to access file
  326. container_image='xingyaoww/od-eval-miniwob:v1.0',
  327. browsergym_eval_env='browsergym/miniwob.choose-list',
  328. )
  329. from opendevin.runtime.browser.browser_env import (
  330. BROWSER_EVAL_GET_GOAL_ACTION,
  331. BROWSER_EVAL_GET_REWARDS_ACTION,
  332. )
  333. # Test browse
  334. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_GOAL_ACTION)
  335. logger.info(action, extra={'msg_type': 'ACTION'})
  336. obs = await runtime.run_action(action)
  337. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  338. assert isinstance(obs, BrowserOutputObservation)
  339. assert not obs.error
  340. assert 'Select' in obs.content
  341. assert 'from the list and click Submit' in obs.content
  342. # Make sure the browser can produce observation in eva[l
  343. action = BrowseInteractiveAction(browser_actions='noop()')
  344. logger.info(action, extra={'msg_type': 'ACTION'})
  345. obs = await runtime.run_action(action)
  346. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  347. assert (
  348. obs.url.strip()
  349. == 'file:///miniwob-plusplus/miniwob/html/miniwob/choose-list.html'
  350. )
  351. # Make sure the rewards are working
  352. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_REWARDS_ACTION)
  353. logger.info(action, extra={'msg_type': 'ACTION'})
  354. obs = await runtime.run_action(action)
  355. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  356. assert json.loads(obs.content) == [0.0]
  357. await runtime.close()
  358. await asyncio.sleep(1)
  359. @pytest.mark.asyncio
  360. async def test_single_multiline_command(temp_dir, box_class):
  361. runtime = await _load_runtime(temp_dir, box_class)
  362. action = CmdRunAction(command='echo \\\n -e "foo"')
  363. logger.info(action, extra={'msg_type': 'ACTION'})
  364. obs = await runtime.run_action(action)
  365. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  366. assert obs.exit_code == 0, 'The exit code should be 0.'
  367. assert 'foo' in obs.content
  368. await runtime.close()
  369. await asyncio.sleep(1)
  370. @pytest.mark.asyncio
  371. async def test_multiline_echo(temp_dir, box_class):
  372. runtime = await _load_runtime(temp_dir, box_class)
  373. action = CmdRunAction(command='echo -e "hello\nworld"')
  374. logger.info(action, extra={'msg_type': 'ACTION'})
  375. obs = await runtime.run_action(action)
  376. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  377. assert obs.exit_code == 0, 'The exit code should be 0.'
  378. assert 'hello\r\nworld' in obs.content
  379. await runtime.close()
  380. await asyncio.sleep(1)
  381. @pytest.mark.asyncio
  382. async def test_runtime_whitespace(temp_dir, box_class):
  383. runtime = await _load_runtime(temp_dir, box_class)
  384. action = CmdRunAction(command='echo -e "\\n\\n\\n"')
  385. logger.info(action, extra={'msg_type': 'ACTION'})
  386. obs = await runtime.run_action(action)
  387. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  388. assert obs.exit_code == 0, 'The exit code should be 0.'
  389. assert '\r\n\r\n\r\n' in obs.content
  390. await runtime.close()
  391. await asyncio.sleep(1)
  392. @pytest.mark.asyncio
  393. async def test_multiple_multiline_commands(temp_dir, box_class, run_as_devin):
  394. cmds = [
  395. 'ls -l',
  396. 'echo -e "hello\nworld"',
  397. """
  398. echo -e "hello it\\'s me"
  399. """.strip(),
  400. """
  401. echo \\
  402. -e 'hello' \\
  403. -v
  404. """.strip(),
  405. """
  406. echo -e 'hello\\nworld\\nare\\nyou\\nthere?'
  407. """.strip(),
  408. """
  409. echo -e 'hello
  410. world
  411. are
  412. you\\n
  413. there?'
  414. """.strip(),
  415. """
  416. echo -e 'hello
  417. world "
  418. '
  419. """.strip(),
  420. ]
  421. joined_cmds = '\n'.join(cmds)
  422. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  423. action = CmdRunAction(command=joined_cmds)
  424. logger.info(action, extra={'msg_type': 'ACTION'})
  425. obs = await runtime.run_action(action)
  426. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  427. assert isinstance(obs, CmdOutputObservation)
  428. assert obs.exit_code == 0, 'The exit code should be 0.'
  429. assert 'total 0' in obs.content
  430. assert 'hello\r\nworld' in obs.content
  431. assert "hello it\\'s me" in obs.content
  432. assert 'hello -v' in obs.content
  433. assert 'hello\r\nworld\r\nare\r\nyou\r\nthere?' in obs.content
  434. assert 'hello\r\nworld\r\nare\r\nyou\r\n\r\nthere?' in obs.content
  435. assert 'hello\r\nworld "\r\n' in obs.content
  436. await runtime.close()
  437. await asyncio.sleep(1)
  438. @pytest.mark.asyncio
  439. async def test_no_ps2_in_output(temp_dir, box_class, run_as_devin):
  440. """Test that the PS2 sign is not added to the output of a multiline command."""
  441. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  442. action = CmdRunAction(command='echo -e "hello\nworld"')
  443. logger.info(action, extra={'msg_type': 'ACTION'})
  444. obs = await runtime.run_action(action)
  445. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  446. assert 'hello\r\nworld' in obs.content
  447. assert '>' not in obs.content
  448. await runtime.close()
  449. await asyncio.sleep(1)
  450. @pytest.mark.asyncio
  451. async def test_multiline_command_loop(temp_dir, box_class):
  452. # https://github.com/OpenDevin/OpenDevin/issues/3143
  453. runtime = await _load_runtime(temp_dir, box_class)
  454. init_cmd = """
  455. mkdir -p _modules && \
  456. for month in {01..04}; do
  457. for day in {01..05}; do
  458. touch "_modules/2024-${month}-${day}-sample.md"
  459. done
  460. done
  461. echo "created files"
  462. """
  463. action = CmdRunAction(command=init_cmd)
  464. logger.info(action, extra={'msg_type': 'ACTION'})
  465. obs = await runtime.run_action(action)
  466. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  467. assert isinstance(obs, CmdOutputObservation)
  468. assert obs.exit_code == 0, 'The exit code should be 0.'
  469. assert 'created files' in obs.content
  470. follow_up_cmd = """
  471. for file in _modules/*.md; do
  472. new_date=$(echo $file | sed -E 's/2024-(01|02|03|04)-/2024-/;s/2024-01/2024-08/;s/2024-02/2024-09/;s/2024-03/2024-10/;s/2024-04/2024-11/')
  473. mv "$file" "$new_date"
  474. done
  475. echo "success"
  476. """
  477. action = CmdRunAction(command=follow_up_cmd)
  478. logger.info(action, extra={'msg_type': 'ACTION'})
  479. obs = await runtime.run_action(action)
  480. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  481. assert isinstance(obs, CmdOutputObservation)
  482. assert obs.exit_code == 0, 'The exit code should be 0.'
  483. assert 'success' in obs.content
  484. await runtime.close()
  485. await asyncio.sleep(1)
  486. @pytest.mark.asyncio
  487. async def test_cmd_run(temp_dir, box_class, run_as_devin):
  488. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  489. action = CmdRunAction(command='ls -l')
  490. logger.info(action, extra={'msg_type': 'ACTION'})
  491. obs = await runtime.run_action(action)
  492. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  493. assert isinstance(obs, CmdOutputObservation)
  494. assert obs.exit_code == 0
  495. assert 'total 0' in obs.content
  496. action = CmdRunAction(command='mkdir test')
  497. logger.info(action, extra={'msg_type': 'ACTION'})
  498. obs = await runtime.run_action(action)
  499. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  500. assert isinstance(obs, CmdOutputObservation)
  501. assert obs.exit_code == 0
  502. action = CmdRunAction(command='ls -l')
  503. logger.info(action, extra={'msg_type': 'ACTION'})
  504. obs = await runtime.run_action(action)
  505. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  506. assert isinstance(obs, CmdOutputObservation)
  507. assert obs.exit_code == 0
  508. if run_as_devin:
  509. assert 'opendevin' in obs.content
  510. else:
  511. assert 'root' in obs.content
  512. assert 'test' in obs.content
  513. action = CmdRunAction(command='touch test/foo.txt')
  514. logger.info(action, extra={'msg_type': 'ACTION'})
  515. obs = await runtime.run_action(action)
  516. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  517. assert isinstance(obs, CmdOutputObservation)
  518. assert obs.exit_code == 0
  519. action = CmdRunAction(command='ls -l test')
  520. logger.info(action, extra={'msg_type': 'ACTION'})
  521. obs = await runtime.run_action(action)
  522. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  523. assert isinstance(obs, CmdOutputObservation)
  524. assert obs.exit_code == 0
  525. assert 'foo.txt' in obs.content
  526. # clean up: this is needed, since CI will not be
  527. # run as root, and this test may leave a file
  528. # owned by root
  529. action = CmdRunAction(command='rm -rf test')
  530. logger.info(action, extra={'msg_type': 'ACTION'})
  531. obs = await runtime.run_action(action)
  532. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  533. assert isinstance(obs, CmdOutputObservation)
  534. assert obs.exit_code == 0
  535. await runtime.close()
  536. await asyncio.sleep(1)
  537. @pytest.mark.asyncio
  538. async def test_run_as_user_correct_home_dir(temp_dir, box_class, run_as_devin):
  539. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  540. action = CmdRunAction(command='cd ~ && pwd')
  541. logger.info(action, extra={'msg_type': 'ACTION'})
  542. obs = await runtime.run_action(action)
  543. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  544. assert isinstance(obs, CmdOutputObservation)
  545. assert obs.exit_code == 0
  546. if run_as_devin:
  547. assert '/home/opendevin' in obs.content
  548. else:
  549. assert '/root' in obs.content
  550. await runtime.close()
  551. await asyncio.sleep(1)
  552. @pytest.mark.asyncio
  553. async def test_multi_cmd_run_in_single_line(temp_dir, box_class):
  554. runtime = await _load_runtime(temp_dir, box_class)
  555. action = CmdRunAction(command='pwd && ls -l')
  556. logger.info(action, extra={'msg_type': 'ACTION'})
  557. obs = await runtime.run_action(action)
  558. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  559. assert isinstance(obs, CmdOutputObservation)
  560. assert obs.exit_code == 0
  561. assert '/workspace' in obs.content
  562. assert 'total 0' in obs.content
  563. await runtime.close()
  564. await asyncio.sleep(1)
  565. @pytest.mark.asyncio
  566. async def test_stateful_cmd(temp_dir, box_class):
  567. runtime = await _load_runtime(temp_dir, box_class)
  568. action = CmdRunAction(command='mkdir test')
  569. logger.info(action, extra={'msg_type': 'ACTION'})
  570. obs = await runtime.run_action(action)
  571. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  572. assert isinstance(obs, CmdOutputObservation)
  573. assert obs.exit_code == 0, 'The exit code should be 0.'
  574. action = CmdRunAction(command='cd test')
  575. logger.info(action, extra={'msg_type': 'ACTION'})
  576. obs = await runtime.run_action(action)
  577. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  578. assert isinstance(obs, CmdOutputObservation)
  579. assert obs.exit_code == 0, 'The exit code should be 0.'
  580. action = CmdRunAction(command='pwd')
  581. logger.info(action, extra={'msg_type': 'ACTION'})
  582. obs = await runtime.run_action(action)
  583. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  584. assert isinstance(obs, CmdOutputObservation)
  585. assert obs.exit_code == 0, 'The exit code should be 0.'
  586. assert '/workspace/test' in obs.content
  587. await runtime.close()
  588. await asyncio.sleep(1)
  589. @pytest.mark.asyncio
  590. async def test_failed_cmd(temp_dir, box_class):
  591. runtime = await _load_runtime(temp_dir, box_class)
  592. action = CmdRunAction(command='non_existing_command')
  593. logger.info(action, extra={'msg_type': 'ACTION'})
  594. obs = await runtime.run_action(action)
  595. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  596. assert isinstance(obs, CmdOutputObservation)
  597. assert obs.exit_code != 0, 'The exit code should not be 0 for a failed command.'
  598. await runtime.close()
  599. await asyncio.sleep(1)
  600. @pytest.mark.asyncio
  601. async def test_ipython_multi_user(temp_dir, box_class, run_as_devin):
  602. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  603. # Test run ipython
  604. # get username
  605. test_code = "import os; print(os.environ['USER'])"
  606. action_ipython = IPythonRunCellAction(code=test_code)
  607. logger.info(action_ipython, extra={'msg_type': 'ACTION'})
  608. obs = await runtime.run_action(action_ipython)
  609. assert isinstance(obs, IPythonRunCellObservation)
  610. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  611. if run_as_devin:
  612. assert 'opendevin' in obs.content
  613. else:
  614. assert 'root' in obs.content
  615. # print pwd
  616. test_code = 'import os; print(os.getcwd())'
  617. action_ipython = IPythonRunCellAction(code=test_code)
  618. logger.info(action_ipython, extra={'msg_type': 'ACTION'})
  619. obs = await runtime.run_action(action_ipython)
  620. assert isinstance(obs, IPythonRunCellObservation)
  621. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  622. assert obs.content.strip() == '/workspace'
  623. # write a file
  624. test_code = "with open('test.txt', 'w') as f: f.write('Hello, world!')"
  625. action_ipython = IPythonRunCellAction(code=test_code)
  626. logger.info(action_ipython, extra={'msg_type': 'ACTION'})
  627. obs = await runtime.run_action(action_ipython)
  628. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  629. assert isinstance(obs, IPythonRunCellObservation)
  630. assert obs.content.strip() == '[Code executed successfully with no output]'
  631. # check file owner via bash
  632. action = CmdRunAction(command='ls -alh test.txt')
  633. logger.info(action, extra={'msg_type': 'ACTION'})
  634. obs = await runtime.run_action(action)
  635. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  636. assert obs.exit_code == 0
  637. if run_as_devin:
  638. # -rw-r--r-- 1 opendevin root 13 Jul 28 03:53 test.txt
  639. assert 'opendevin' in obs.content.split('\r\n')[0]
  640. assert 'root' in obs.content.split('\r\n')[0]
  641. else:
  642. # -rw-r--r-- 1 root root 13 Jul 28 03:53 test.txt
  643. assert 'root' in obs.content.split('\r\n')[0]
  644. # clean up
  645. action = CmdRunAction(command='rm -rf test')
  646. logger.info(action, extra={'msg_type': 'ACTION'})
  647. obs = await runtime.run_action(action)
  648. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  649. assert obs.exit_code == 0
  650. await runtime.close()
  651. await asyncio.sleep(1)
  652. @pytest.mark.asyncio
  653. async def test_ipython_simple(temp_dir, box_class):
  654. runtime = await _load_runtime(temp_dir, box_class)
  655. # Test run ipython
  656. # get username
  657. test_code = 'print(1)'
  658. action_ipython = IPythonRunCellAction(code=test_code)
  659. logger.info(action_ipython, extra={'msg_type': 'ACTION'})
  660. obs = await runtime.run_action(action_ipython)
  661. assert isinstance(obs, IPythonRunCellObservation)
  662. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  663. assert obs.content.strip() == '1'
  664. await runtime.close()
  665. await asyncio.sleep(1)
  666. async def _test_ipython_agentskills_fileop_pwd_impl(
  667. runtime: EventStreamRuntime, enable_auto_lint: bool
  668. ):
  669. # remove everything in /workspace
  670. action = CmdRunAction(command='rm -rf /workspace/*')
  671. logger.info(action, extra={'msg_type': 'ACTION'})
  672. obs = await runtime.run_action(action)
  673. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  674. assert obs.exit_code == 0
  675. action = CmdRunAction(command='mkdir test')
  676. logger.info(action, extra={'msg_type': 'ACTION'})
  677. obs = await runtime.run_action(action)
  678. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  679. assert isinstance(obs, CmdOutputObservation)
  680. assert obs.exit_code == 0
  681. action = IPythonRunCellAction(code="create_file('hello.py')")
  682. logger.info(action, extra={'msg_type': 'ACTION'})
  683. obs = await runtime.run_action(action)
  684. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  685. assert isinstance(obs, IPythonRunCellObservation)
  686. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  687. '[File: /workspace/hello.py (1 lines total)]\n'
  688. '(this is the beginning of the file)\n'
  689. '1|\n'
  690. '(this is the end of the file)\n'
  691. '[File hello.py created.]\n'
  692. ).strip().split('\n')
  693. action = CmdRunAction(command='cd test')
  694. logger.info(action, extra={'msg_type': 'ACTION'})
  695. obs = await runtime.run_action(action)
  696. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  697. assert isinstance(obs, CmdOutputObservation)
  698. assert obs.exit_code == 0
  699. # This should create a file in the current working directory
  700. # i.e., /workspace/test/hello.py instead of /workspace/hello.py
  701. action = IPythonRunCellAction(code="create_file('hello.py')")
  702. logger.info(action, extra={'msg_type': 'ACTION'})
  703. obs = await runtime.run_action(action)
  704. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  705. assert isinstance(obs, IPythonRunCellObservation)
  706. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  707. '[File: /workspace/test/hello.py (1 lines total)]\n'
  708. '(this is the beginning of the file)\n'
  709. '1|\n'
  710. '(this is the end of the file)\n'
  711. '[File hello.py created.]\n'
  712. ).strip().split('\n')
  713. if enable_auto_lint:
  714. # edit file, but make a mistake in indentation
  715. action = IPythonRunCellAction(
  716. code="insert_content_at_line('hello.py', 1, ' print(\"hello world\")')"
  717. )
  718. logger.info(action, extra={'msg_type': 'ACTION'})
  719. obs = await runtime.run_action(action)
  720. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  721. assert isinstance(obs, IPythonRunCellObservation)
  722. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  723. """
  724. [Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]
  725. ERRORS:
  726. /workspace/test/hello.py:1:3: E999 IndentationError: unexpected indent
  727. [This is how your edit would have looked if applied]
  728. -------------------------------------------------
  729. (this is the beginning of the file)
  730. 1| print("hello world")
  731. (this is the end of the file)
  732. -------------------------------------------------
  733. [This is the original code before your edit]
  734. -------------------------------------------------
  735. (this is the beginning of the file)
  736. 1|
  737. (this is the end of the file)
  738. -------------------------------------------------
  739. Your changes have NOT been applied. Please fix your edit command and try again.
  740. You either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.
  741. DO NOT re-run the same failed edit command. Running it again will lead to the same error.
  742. """
  743. ).strip().split('\n')
  744. # edit file with correct indentation
  745. action = IPythonRunCellAction(
  746. code="insert_content_at_line('hello.py', 1, 'print(\"hello world\")')"
  747. )
  748. logger.info(action, extra={'msg_type': 'ACTION'})
  749. obs = await runtime.run_action(action)
  750. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  751. assert isinstance(obs, IPythonRunCellObservation)
  752. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  753. """
  754. [File: /workspace/test/hello.py (1 lines total after edit)]
  755. (this is the beginning of the file)
  756. 1|print("hello world")
  757. (this is the end of the file)
  758. [File updated (edited at line 1). Please review the changes and make sure they are correct (correct indentation, no duplicate lines, etc). Edit the file again if necessary.]
  759. """
  760. ).strip().split('\n')
  761. action = CmdRunAction(command='rm -rf /workspace/*')
  762. logger.info(action, extra={'msg_type': 'ACTION'})
  763. obs = await runtime.run_action(action)
  764. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  765. assert obs.exit_code == 0
  766. await runtime.close()
  767. await asyncio.sleep(1)
  768. @pytest.mark.asyncio
  769. async def test_ipython_agentskills_fileop_pwd(
  770. temp_dir, box_class, run_as_devin, enable_auto_lint
  771. ):
  772. """Make sure that cd in bash also update the current working directory in ipython."""
  773. runtime = await _load_runtime(
  774. temp_dir, box_class, run_as_devin, enable_auto_lint=enable_auto_lint
  775. )
  776. await _test_ipython_agentskills_fileop_pwd_impl(runtime, enable_auto_lint)
  777. await runtime.close()
  778. await asyncio.sleep(1)
  779. @pytest.mark.asyncio
  780. async def test_ipython_agentskills_fileop_pwd_with_userdir(temp_dir, box_class):
  781. """Make sure that cd in bash also update the current working directory in ipython.
  782. Handle special case where the pwd is provided as "~", which should be expanded using os.path.expanduser
  783. on the client side.
  784. """
  785. runtime = await _load_runtime(
  786. temp_dir,
  787. box_class,
  788. run_as_devin=False,
  789. )
  790. action = CmdRunAction(command='cd ~')
  791. logger.info(action, extra={'msg_type': 'ACTION'})
  792. obs = await runtime.run_action(action)
  793. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  794. assert obs.exit_code == 0
  795. action = CmdRunAction(command='mkdir test && ls -la')
  796. logger.info(action, extra={'msg_type': 'ACTION'})
  797. obs = await runtime.run_action(action)
  798. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  799. assert isinstance(obs, CmdOutputObservation)
  800. assert obs.exit_code == 0
  801. action = IPythonRunCellAction(code="create_file('hello.py')")
  802. logger.info(action, extra={'msg_type': 'ACTION'})
  803. obs = await runtime.run_action(action)
  804. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  805. assert isinstance(obs, IPythonRunCellObservation)
  806. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  807. '[File: /root/hello.py (1 lines total)]\n'
  808. '(this is the beginning of the file)\n'
  809. '1|\n'
  810. '(this is the end of the file)\n'
  811. '[File hello.py created.]\n'
  812. ).strip().split('\n')
  813. action = CmdRunAction(command='cd test')
  814. logger.info(action, extra={'msg_type': 'ACTION'})
  815. obs = await runtime.run_action(action)
  816. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  817. assert isinstance(obs, CmdOutputObservation)
  818. assert obs.exit_code == 0
  819. # This should create a file in the current working directory
  820. # i.e., /workspace/test/hello.py instead of /workspace/hello.py
  821. action = IPythonRunCellAction(code="create_file('hello.py')")
  822. logger.info(action, extra={'msg_type': 'ACTION'})
  823. obs = await runtime.run_action(action)
  824. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  825. assert isinstance(obs, IPythonRunCellObservation)
  826. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  827. '[File: /root/test/hello.py (1 lines total)]\n'
  828. '(this is the beginning of the file)\n'
  829. '1|\n'
  830. '(this is the end of the file)\n'
  831. '[File hello.py created.]\n'
  832. ).strip().split('\n')
  833. await runtime.close()
  834. await asyncio.sleep(1)
  835. @pytest.mark.asyncio
  836. async def test_bash_python_version(temp_dir, box_class):
  837. """Make sure Python is available in bash."""
  838. runtime = await _load_runtime(temp_dir, box_class)
  839. action = CmdRunAction(command='which python')
  840. logger.info(action, extra={'msg_type': 'ACTION'})
  841. obs = await runtime.run_action(action)
  842. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  843. assert obs.exit_code == 0
  844. action = CmdRunAction(command='python --version')
  845. logger.info(action, extra={'msg_type': 'ACTION'})
  846. obs = await runtime.run_action(action)
  847. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  848. assert obs.exit_code == 0
  849. # Should not error out
  850. action = CmdRunAction(command='pip --version')
  851. logger.info(action, extra={'msg_type': 'ACTION'})
  852. obs = await runtime.run_action(action)
  853. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  854. assert obs.exit_code == 0
  855. # Should not error out
  856. await runtime.close()
  857. await asyncio.sleep(1)
  858. @pytest.mark.asyncio
  859. async def test_ipython_package_install(temp_dir, box_class, run_as_devin):
  860. """Make sure that cd in bash also update the current working directory in ipython."""
  861. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  862. # It should error out since pymsgbox is not installed
  863. action = IPythonRunCellAction(code='import pymsgbox')
  864. logger.info(action, extra={'msg_type': 'ACTION'})
  865. obs = await runtime.run_action(action)
  866. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  867. assert "ModuleNotFoundError: No module named 'pymsgbox'" in obs.content
  868. # Install pymsgbox in Jupyter
  869. action = IPythonRunCellAction(code='%pip install pymsgbox==1.0.9')
  870. logger.info(action, extra={'msg_type': 'ACTION'})
  871. obs = await runtime.run_action(action)
  872. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  873. assert (
  874. 'Successfully installed pymsgbox-1.0.9' in obs.content
  875. or '[Package installed successfully]' in obs.content
  876. )
  877. action = IPythonRunCellAction(code='import pymsgbox')
  878. logger.info(action, extra={'msg_type': 'ACTION'})
  879. obs = await runtime.run_action(action)
  880. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  881. # import should not error out
  882. assert obs.content.strip() == '[Code executed successfully with no output]'
  883. await runtime.close()
  884. await asyncio.sleep(1)
  885. def _create_test_file(host_temp_dir):
  886. # Single file
  887. with open(os.path.join(host_temp_dir, 'test_file.txt'), 'w') as f:
  888. f.write('Hello, World!')
  889. @pytest.mark.asyncio
  890. async def test_copy_single_file(temp_dir, box_class):
  891. runtime = await _load_runtime(temp_dir, box_class)
  892. with tempfile.TemporaryDirectory() as host_temp_dir:
  893. _create_test_file(host_temp_dir)
  894. await runtime.copy_to(
  895. os.path.join(host_temp_dir, 'test_file.txt'), '/workspace'
  896. )
  897. action = CmdRunAction(command='ls -alh /workspace')
  898. logger.info(action, extra={'msg_type': 'ACTION'})
  899. obs = await runtime.run_action(action)
  900. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  901. assert isinstance(obs, CmdOutputObservation)
  902. assert obs.exit_code == 0
  903. assert 'test_file.txt' in obs.content
  904. action = CmdRunAction(command='cat /workspace/test_file.txt')
  905. logger.info(action, extra={'msg_type': 'ACTION'})
  906. obs = await runtime.run_action(action)
  907. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  908. assert isinstance(obs, CmdOutputObservation)
  909. assert obs.exit_code == 0
  910. assert 'Hello, World!' in obs.content
  911. await runtime.close()
  912. await asyncio.sleep(1)
  913. def _create_test_dir_with_files(host_temp_dir):
  914. os.mkdir(os.path.join(host_temp_dir, 'test_dir'))
  915. with open(os.path.join(host_temp_dir, 'test_dir', 'file1.txt'), 'w') as f:
  916. f.write('File 1 content')
  917. with open(os.path.join(host_temp_dir, 'test_dir', 'file2.txt'), 'w') as f:
  918. f.write('File 2 content')
  919. @pytest.mark.asyncio
  920. async def test_copy_directory_recursively(temp_dir, box_class):
  921. runtime = await _load_runtime(temp_dir, box_class)
  922. with tempfile.TemporaryDirectory() as host_temp_dir:
  923. # We need a separate directory, since temp_dir is mounted to /workspace
  924. _create_test_dir_with_files(host_temp_dir)
  925. await runtime.copy_to(
  926. os.path.join(host_temp_dir, 'test_dir'), '/workspace', recursive=True
  927. )
  928. action = CmdRunAction(command='ls -alh /workspace')
  929. logger.info(action, extra={'msg_type': 'ACTION'})
  930. obs = await runtime.run_action(action)
  931. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  932. assert isinstance(obs, CmdOutputObservation)
  933. assert obs.exit_code == 0
  934. assert 'test_dir' in obs.content
  935. assert 'file1.txt' not in obs.content
  936. assert 'file2.txt' not in obs.content
  937. action = CmdRunAction(command='ls -alh /workspace/test_dir')
  938. logger.info(action, extra={'msg_type': 'ACTION'})
  939. obs = await runtime.run_action(action)
  940. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  941. assert isinstance(obs, CmdOutputObservation)
  942. assert obs.exit_code == 0
  943. assert 'file1.txt' in obs.content
  944. assert 'file2.txt' in obs.content
  945. action = CmdRunAction(command='cat /workspace/test_dir/file1.txt')
  946. logger.info(action, extra={'msg_type': 'ACTION'})
  947. obs = await runtime.run_action(action)
  948. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  949. assert isinstance(obs, CmdOutputObservation)
  950. assert obs.exit_code == 0
  951. assert 'File 1 content' in obs.content
  952. await runtime.close()
  953. await asyncio.sleep(1)
  954. @pytest.mark.asyncio
  955. async def test_copy_to_non_existent_directory(temp_dir, box_class):
  956. runtime = await _load_runtime(temp_dir, box_class)
  957. with tempfile.TemporaryDirectory() as host_temp_dir:
  958. _create_test_file(host_temp_dir)
  959. await runtime.copy_to(
  960. os.path.join(host_temp_dir, 'test_file.txt'), '/workspace/new_dir'
  961. )
  962. action = CmdRunAction(command='cat /workspace/new_dir/test_file.txt')
  963. logger.info(action, extra={'msg_type': 'ACTION'})
  964. obs = await runtime.run_action(action)
  965. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  966. assert isinstance(obs, CmdOutputObservation)
  967. assert obs.exit_code == 0
  968. assert 'Hello, World!' in obs.content
  969. await runtime.close()
  970. await asyncio.sleep(1)
  971. @pytest.mark.asyncio
  972. async def test_overwrite_existing_file(temp_dir, box_class):
  973. runtime = await _load_runtime(temp_dir, box_class)
  974. # touch a file in /workspace
  975. action = CmdRunAction(command='touch /workspace/test_file.txt')
  976. logger.info(action, extra={'msg_type': 'ACTION'})
  977. obs = await runtime.run_action(action)
  978. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  979. assert isinstance(obs, CmdOutputObservation)
  980. assert obs.exit_code == 0
  981. action = CmdRunAction(command='cat /workspace/test_file.txt')
  982. logger.info(action, extra={'msg_type': 'ACTION'})
  983. obs = await runtime.run_action(action)
  984. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  985. assert isinstance(obs, CmdOutputObservation)
  986. assert obs.exit_code == 0
  987. assert 'Hello, World!' not in obs.content
  988. with tempfile.TemporaryDirectory() as host_temp_dir:
  989. _create_test_file(host_temp_dir)
  990. await runtime.copy_to(
  991. os.path.join(host_temp_dir, 'test_file.txt'), '/workspace'
  992. )
  993. action = CmdRunAction(command='cat /workspace/test_file.txt')
  994. logger.info(action, extra={'msg_type': 'ACTION'})
  995. obs = await runtime.run_action(action)
  996. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  997. assert isinstance(obs, CmdOutputObservation)
  998. assert obs.exit_code == 0
  999. assert 'Hello, World!' in obs.content
  1000. await runtime.close()
  1001. await asyncio.sleep(1)
  1002. @pytest.mark.asyncio
  1003. async def test_copy_non_existent_file(temp_dir, box_class):
  1004. runtime = await _load_runtime(temp_dir, box_class)
  1005. with pytest.raises(FileNotFoundError):
  1006. await runtime.copy_to(
  1007. os.path.join(temp_dir, 'non_existent_file.txt'),
  1008. '/workspace/should_not_exist.txt',
  1009. )
  1010. action = CmdRunAction(command='ls /workspace/should_not_exist.txt')
  1011. logger.info(action, extra={'msg_type': 'ACTION'})
  1012. obs = await runtime.run_action(action)
  1013. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1014. assert isinstance(obs, CmdOutputObservation)
  1015. assert obs.exit_code != 0 # File should not exist
  1016. await runtime.close()
  1017. await asyncio.sleep(1)
  1018. @pytest.mark.asyncio
  1019. async def test_keep_prompt(temp_dir):
  1020. # only EventStreamRuntime supports keep_prompt
  1021. runtime = await _load_runtime(
  1022. temp_dir, box_class=EventStreamRuntime, run_as_devin=False
  1023. )
  1024. action = CmdRunAction(command='touch /workspace/test_file.txt')
  1025. logger.info(action, extra={'msg_type': 'ACTION'})
  1026. obs = await runtime.run_action(action)
  1027. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1028. assert isinstance(obs, CmdOutputObservation)
  1029. assert obs.exit_code == 0
  1030. assert 'root@' in obs.content
  1031. action = CmdRunAction(command='cat /workspace/test_file.txt', keep_prompt=False)
  1032. logger.info(action, extra={'msg_type': 'ACTION'})
  1033. obs = await runtime.run_action(action)
  1034. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1035. assert isinstance(obs, CmdOutputObservation)
  1036. assert obs.exit_code == 0
  1037. assert 'root@' not in obs.content
  1038. await runtime.close()
  1039. await asyncio.sleep(1)
  1040. @pytest.mark.asyncio
  1041. async def test_git_operation(box_class):
  1042. # do not mount workspace, since workspace mount by tests will be owned by root
  1043. # while the user_id we get via os.getuid() is different from root
  1044. # which causes permission issues
  1045. runtime = await _load_runtime(
  1046. temp_dir=None,
  1047. box_class=box_class,
  1048. # Need to use non-root user to expose issues
  1049. run_as_devin=True,
  1050. )
  1051. # this will happen if permission of runtime is not properly configured
  1052. # fatal: detected dubious ownership in repository at '/workspace'
  1053. # check the ownership of the current directory
  1054. action = CmdRunAction(command='ls -alh .')
  1055. logger.info(action, extra={'msg_type': 'ACTION'})
  1056. obs = await runtime.run_action(action)
  1057. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1058. assert isinstance(obs, CmdOutputObservation)
  1059. assert obs.exit_code == 0
  1060. # drwx--S--- 2 opendevin root 64 Aug 7 23:32 .
  1061. # drwxr-xr-x 1 root root 4.0K Aug 7 23:33 ..
  1062. for line in obs.content.split('\r\n'):
  1063. if ' ..' in line:
  1064. # parent directory should be owned by root
  1065. assert 'root' in line
  1066. assert 'opendevin' not in line
  1067. elif ' .' in line:
  1068. # current directory should be owned by opendevin
  1069. # and its group should be root
  1070. assert 'opendevin' in line
  1071. assert 'root' in line
  1072. # make sure all git operations are allowed
  1073. action = CmdRunAction(command='git init')
  1074. logger.info(action, extra={'msg_type': 'ACTION'})
  1075. obs = await runtime.run_action(action)
  1076. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1077. assert isinstance(obs, CmdOutputObservation)
  1078. assert obs.exit_code == 0
  1079. # create a file
  1080. action = CmdRunAction(command='echo "hello" > test_file.txt')
  1081. logger.info(action, extra={'msg_type': 'ACTION'})
  1082. obs = await runtime.run_action(action)
  1083. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1084. assert isinstance(obs, CmdOutputObservation)
  1085. assert obs.exit_code == 0
  1086. # git add
  1087. action = CmdRunAction(command='git add test_file.txt')
  1088. logger.info(action, extra={'msg_type': 'ACTION'})
  1089. obs = await runtime.run_action(action)
  1090. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1091. assert isinstance(obs, CmdOutputObservation)
  1092. assert obs.exit_code == 0
  1093. # git diff
  1094. action = CmdRunAction(command='git diff')
  1095. logger.info(action, extra={'msg_type': 'ACTION'})
  1096. obs = await runtime.run_action(action)
  1097. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1098. assert isinstance(obs, CmdOutputObservation)
  1099. assert obs.exit_code == 0
  1100. # git commit
  1101. action = CmdRunAction(command='git commit -m "test commit"')
  1102. logger.info(action, extra={'msg_type': 'ACTION'})
  1103. obs = await runtime.run_action(action)
  1104. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1105. assert isinstance(obs, CmdOutputObservation)
  1106. assert obs.exit_code == 0
  1107. await runtime.close()
  1108. await runtime.close()
  1109. await asyncio.sleep(1)