test_runtime.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  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 (
  246. obs.content.strip()
  247. == 'Hello, `World`!\n[Jupyter current working directory: /workspace]'
  248. )
  249. # Test read file (file should not exist)
  250. action_read = FileReadAction(path='hello.sh')
  251. logger.info(action_read, extra={'msg_type': 'ACTION'})
  252. obs = await runtime.run_action(action_read)
  253. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  254. assert isinstance(obs, ErrorObservation)
  255. assert 'File not found' in obs.content
  256. # Test write file
  257. action_write = FileWriteAction(content='echo "Hello, World!"', path='hello.sh')
  258. logger.info(action_write, extra={'msg_type': 'ACTION'})
  259. obs = await runtime.run_action(action_write)
  260. assert isinstance(obs, FileWriteObservation)
  261. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  262. assert obs.content == ''
  263. # event stream runtime will always use absolute path
  264. assert obs.path == '/workspace/hello.sh'
  265. # Test read file (file should exist)
  266. action_read = FileReadAction(path='hello.sh')
  267. logger.info(action_read, extra={'msg_type': 'ACTION'})
  268. obs = await runtime.run_action(action_read)
  269. assert isinstance(
  270. obs, FileReadObservation
  271. ), 'The observation should be a FileReadObservation.'
  272. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  273. assert obs.content == 'echo "Hello, World!"\n'
  274. assert obs.path == '/workspace/hello.sh'
  275. # clean up
  276. action = CmdRunAction(command='rm -rf hello.sh')
  277. logger.info(action, extra={'msg_type': 'ACTION'})
  278. obs = await runtime.run_action(action)
  279. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  280. assert obs.exit_code == 0
  281. await runtime.close()
  282. await asyncio.sleep(1)
  283. @pytest.mark.asyncio
  284. async def test_simple_browse(temp_dir, box_class, run_as_devin):
  285. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  286. # Test browse
  287. action_cmd = CmdRunAction(
  288. command=f'{PY3_FOR_TESTING} -m http.server 8000 > server.log 2>&1 &'
  289. )
  290. logger.info(action_cmd, extra={'msg_type': 'ACTION'})
  291. obs = await runtime.run_action(action_cmd)
  292. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  293. assert isinstance(obs, CmdOutputObservation)
  294. assert obs.exit_code == 0
  295. assert '[1]' in obs.content
  296. action_cmd = CmdRunAction(command='sleep 5 && cat server.log')
  297. logger.info(action_cmd, extra={'msg_type': 'ACTION'})
  298. obs = await runtime.run_action(action_cmd)
  299. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  300. assert obs.exit_code == 0
  301. action_browse = BrowseURLAction(url='http://localhost:8000')
  302. logger.info(action_browse, extra={'msg_type': 'ACTION'})
  303. obs = await runtime.run_action(action_browse)
  304. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  305. assert isinstance(obs, BrowserOutputObservation)
  306. assert 'http://localhost:8000' in obs.url
  307. assert not obs.error
  308. assert obs.open_pages_urls == ['http://localhost:8000/']
  309. assert obs.active_page_index == 0
  310. assert obs.last_browser_action == 'goto("http://localhost:8000")'
  311. assert obs.last_browser_action_error == ''
  312. assert 'Directory listing for /' in obs.content
  313. assert 'server.log' in obs.content
  314. # clean up
  315. action = CmdRunAction(command='rm -rf server.log')
  316. logger.info(action, extra={'msg_type': 'ACTION'})
  317. obs = await runtime.run_action(action)
  318. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  319. assert obs.exit_code == 0
  320. await runtime.close()
  321. await asyncio.sleep(1)
  322. @pytest.mark.asyncio
  323. async def test_browsergym_eval_env(temp_dir):
  324. runtime = await _load_runtime(
  325. temp_dir,
  326. # only supported in event stream runtime
  327. box_class=EventStreamRuntime,
  328. run_as_devin=False, # need root permission to access file
  329. container_image='xingyaoww/od-eval-miniwob:v1.0',
  330. browsergym_eval_env='browsergym/miniwob.choose-list',
  331. )
  332. from opendevin.runtime.browser.browser_env import (
  333. BROWSER_EVAL_GET_GOAL_ACTION,
  334. BROWSER_EVAL_GET_REWARDS_ACTION,
  335. )
  336. # Test browse
  337. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_GOAL_ACTION)
  338. logger.info(action, extra={'msg_type': 'ACTION'})
  339. obs = await runtime.run_action(action)
  340. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  341. assert isinstance(obs, BrowserOutputObservation)
  342. assert not obs.error
  343. assert 'Select' in obs.content
  344. assert 'from the list and click Submit' in obs.content
  345. # Make sure the browser can produce observation in eva[l
  346. action = BrowseInteractiveAction(browser_actions='noop()')
  347. logger.info(action, extra={'msg_type': 'ACTION'})
  348. obs = await runtime.run_action(action)
  349. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  350. assert (
  351. obs.url.strip()
  352. == 'file:///miniwob-plusplus/miniwob/html/miniwob/choose-list.html'
  353. )
  354. # Make sure the rewards are working
  355. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_REWARDS_ACTION)
  356. logger.info(action, extra={'msg_type': 'ACTION'})
  357. obs = await runtime.run_action(action)
  358. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  359. assert json.loads(obs.content) == [0.0]
  360. await runtime.close()
  361. await asyncio.sleep(1)
  362. @pytest.mark.asyncio
  363. async def test_single_multiline_command(temp_dir, box_class):
  364. runtime = await _load_runtime(temp_dir, box_class)
  365. action = CmdRunAction(command='echo \\\n -e "foo"')
  366. logger.info(action, extra={'msg_type': 'ACTION'})
  367. obs = await runtime.run_action(action)
  368. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  369. assert obs.exit_code == 0, 'The exit code should be 0.'
  370. assert 'foo' in obs.content
  371. await runtime.close()
  372. await asyncio.sleep(1)
  373. @pytest.mark.asyncio
  374. async def test_multiline_echo(temp_dir, box_class):
  375. runtime = await _load_runtime(temp_dir, box_class)
  376. action = CmdRunAction(command='echo -e "hello\nworld"')
  377. logger.info(action, extra={'msg_type': 'ACTION'})
  378. obs = await runtime.run_action(action)
  379. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  380. assert obs.exit_code == 0, 'The exit code should be 0.'
  381. assert 'hello\r\nworld' in obs.content
  382. await runtime.close()
  383. await asyncio.sleep(1)
  384. @pytest.mark.asyncio
  385. async def test_runtime_whitespace(temp_dir, box_class):
  386. runtime = await _load_runtime(temp_dir, box_class)
  387. action = CmdRunAction(command='echo -e "\\n\\n\\n"')
  388. logger.info(action, extra={'msg_type': 'ACTION'})
  389. obs = await runtime.run_action(action)
  390. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  391. assert obs.exit_code == 0, 'The exit code should be 0.'
  392. assert '\r\n\r\n\r\n' in obs.content
  393. await runtime.close()
  394. await asyncio.sleep(1)
  395. @pytest.mark.asyncio
  396. async def test_multiple_multiline_commands(temp_dir, box_class, run_as_devin):
  397. cmds = [
  398. 'ls -l',
  399. 'echo -e "hello\nworld"',
  400. """
  401. echo -e "hello it\\'s me"
  402. """.strip(),
  403. """
  404. echo \\
  405. -e 'hello' \\
  406. -v
  407. """.strip(),
  408. """
  409. echo -e 'hello\\nworld\\nare\\nyou\\nthere?'
  410. """.strip(),
  411. """
  412. echo -e 'hello
  413. world
  414. are
  415. you\\n
  416. there?'
  417. """.strip(),
  418. """
  419. echo -e 'hello
  420. world "
  421. '
  422. """.strip(),
  423. ]
  424. joined_cmds = '\n'.join(cmds)
  425. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  426. action = CmdRunAction(command=joined_cmds)
  427. logger.info(action, extra={'msg_type': 'ACTION'})
  428. obs = await runtime.run_action(action)
  429. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  430. assert isinstance(obs, CmdOutputObservation)
  431. assert obs.exit_code == 0, 'The exit code should be 0.'
  432. assert 'total 0' in obs.content
  433. assert 'hello\r\nworld' in obs.content
  434. assert "hello it\\'s me" in obs.content
  435. assert 'hello -v' in obs.content
  436. assert 'hello\r\nworld\r\nare\r\nyou\r\nthere?' in obs.content
  437. assert 'hello\r\nworld\r\nare\r\nyou\r\n\r\nthere?' in obs.content
  438. assert 'hello\r\nworld "\r\n' in obs.content
  439. await runtime.close()
  440. await asyncio.sleep(1)
  441. @pytest.mark.asyncio
  442. async def test_no_ps2_in_output(temp_dir, box_class, run_as_devin):
  443. """Test that the PS2 sign is not added to the output of a multiline command."""
  444. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  445. action = CmdRunAction(command='echo -e "hello\nworld"')
  446. logger.info(action, extra={'msg_type': 'ACTION'})
  447. obs = await runtime.run_action(action)
  448. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  449. assert 'hello\r\nworld' in obs.content
  450. assert '>' not in obs.content
  451. await runtime.close()
  452. await asyncio.sleep(1)
  453. @pytest.mark.asyncio
  454. async def test_multiline_command_loop(temp_dir, box_class):
  455. # https://github.com/OpenDevin/OpenDevin/issues/3143
  456. runtime = await _load_runtime(temp_dir, box_class)
  457. init_cmd = """
  458. mkdir -p _modules && \
  459. for month in {01..04}; do
  460. for day in {01..05}; do
  461. touch "_modules/2024-${month}-${day}-sample.md"
  462. done
  463. done
  464. echo "created files"
  465. """
  466. action = CmdRunAction(command=init_cmd)
  467. logger.info(action, extra={'msg_type': 'ACTION'})
  468. obs = await runtime.run_action(action)
  469. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  470. assert isinstance(obs, CmdOutputObservation)
  471. assert obs.exit_code == 0, 'The exit code should be 0.'
  472. assert 'created files' in obs.content
  473. follow_up_cmd = """
  474. for file in _modules/*.md; do
  475. 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/')
  476. mv "$file" "$new_date"
  477. done
  478. echo "success"
  479. """
  480. action = CmdRunAction(command=follow_up_cmd)
  481. logger.info(action, extra={'msg_type': 'ACTION'})
  482. obs = await runtime.run_action(action)
  483. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  484. assert isinstance(obs, CmdOutputObservation)
  485. assert obs.exit_code == 0, 'The exit code should be 0.'
  486. assert 'success' in obs.content
  487. await runtime.close()
  488. await asyncio.sleep(1)
  489. @pytest.mark.asyncio
  490. async def test_cmd_run(temp_dir, box_class, run_as_devin):
  491. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  492. action = CmdRunAction(command='ls -l')
  493. logger.info(action, extra={'msg_type': 'ACTION'})
  494. obs = await runtime.run_action(action)
  495. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  496. assert isinstance(obs, CmdOutputObservation)
  497. assert obs.exit_code == 0
  498. assert 'total 0' in obs.content
  499. action = CmdRunAction(command='mkdir test')
  500. logger.info(action, extra={'msg_type': 'ACTION'})
  501. obs = await runtime.run_action(action)
  502. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  503. assert isinstance(obs, CmdOutputObservation)
  504. assert obs.exit_code == 0
  505. action = CmdRunAction(command='ls -l')
  506. logger.info(action, extra={'msg_type': 'ACTION'})
  507. obs = await runtime.run_action(action)
  508. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  509. assert isinstance(obs, CmdOutputObservation)
  510. assert obs.exit_code == 0
  511. if run_as_devin:
  512. assert 'opendevin' in obs.content
  513. else:
  514. assert 'root' in obs.content
  515. assert 'test' in obs.content
  516. action = CmdRunAction(command='touch test/foo.txt')
  517. logger.info(action, extra={'msg_type': 'ACTION'})
  518. obs = await runtime.run_action(action)
  519. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  520. assert isinstance(obs, CmdOutputObservation)
  521. assert obs.exit_code == 0
  522. action = CmdRunAction(command='ls -l test')
  523. logger.info(action, extra={'msg_type': 'ACTION'})
  524. obs = await runtime.run_action(action)
  525. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  526. assert isinstance(obs, CmdOutputObservation)
  527. assert obs.exit_code == 0
  528. assert 'foo.txt' in obs.content
  529. # clean up: this is needed, since CI will not be
  530. # run as root, and this test may leave a file
  531. # owned by root
  532. action = CmdRunAction(command='rm -rf test')
  533. logger.info(action, extra={'msg_type': 'ACTION'})
  534. obs = await runtime.run_action(action)
  535. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  536. assert isinstance(obs, CmdOutputObservation)
  537. assert obs.exit_code == 0
  538. await runtime.close()
  539. await asyncio.sleep(1)
  540. @pytest.mark.asyncio
  541. async def test_run_as_user_correct_home_dir(temp_dir, box_class, run_as_devin):
  542. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  543. action = CmdRunAction(command='cd ~ && pwd')
  544. logger.info(action, extra={'msg_type': 'ACTION'})
  545. obs = await runtime.run_action(action)
  546. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  547. assert isinstance(obs, CmdOutputObservation)
  548. assert obs.exit_code == 0
  549. if run_as_devin:
  550. assert '/home/opendevin' in obs.content
  551. else:
  552. assert '/root' in obs.content
  553. await runtime.close()
  554. await asyncio.sleep(1)
  555. @pytest.mark.asyncio
  556. async def test_multi_cmd_run_in_single_line(temp_dir, box_class):
  557. runtime = await _load_runtime(temp_dir, box_class)
  558. action = CmdRunAction(command='pwd && ls -l')
  559. logger.info(action, extra={'msg_type': 'ACTION'})
  560. obs = await runtime.run_action(action)
  561. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  562. assert isinstance(obs, CmdOutputObservation)
  563. assert obs.exit_code == 0
  564. assert '/workspace' in obs.content
  565. assert 'total 0' in obs.content
  566. await runtime.close()
  567. await asyncio.sleep(1)
  568. @pytest.mark.asyncio
  569. async def test_stateful_cmd(temp_dir, box_class):
  570. runtime = await _load_runtime(temp_dir, box_class)
  571. action = CmdRunAction(command='mkdir test')
  572. logger.info(action, extra={'msg_type': 'ACTION'})
  573. obs = await runtime.run_action(action)
  574. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  575. assert isinstance(obs, CmdOutputObservation)
  576. assert obs.exit_code == 0, 'The exit code should be 0.'
  577. action = CmdRunAction(command='cd test')
  578. logger.info(action, extra={'msg_type': 'ACTION'})
  579. obs = await runtime.run_action(action)
  580. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  581. assert isinstance(obs, CmdOutputObservation)
  582. assert obs.exit_code == 0, 'The exit code should be 0.'
  583. action = CmdRunAction(command='pwd')
  584. logger.info(action, extra={'msg_type': 'ACTION'})
  585. obs = await runtime.run_action(action)
  586. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  587. assert isinstance(obs, CmdOutputObservation)
  588. assert obs.exit_code == 0, 'The exit code should be 0.'
  589. assert '/workspace/test' in obs.content
  590. await runtime.close()
  591. await asyncio.sleep(1)
  592. @pytest.mark.asyncio
  593. async def test_failed_cmd(temp_dir, box_class):
  594. runtime = await _load_runtime(temp_dir, box_class)
  595. action = CmdRunAction(command='non_existing_command')
  596. logger.info(action, extra={'msg_type': 'ACTION'})
  597. obs = await runtime.run_action(action)
  598. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  599. assert isinstance(obs, CmdOutputObservation)
  600. assert obs.exit_code != 0, 'The exit code should not be 0 for a failed command.'
  601. await runtime.close()
  602. await asyncio.sleep(1)
  603. @pytest.mark.asyncio
  604. async def test_ipython_multi_user(temp_dir, box_class, run_as_devin):
  605. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  606. # Test run ipython
  607. # get username
  608. test_code = "import os; print(os.environ['USER'])"
  609. action_ipython = IPythonRunCellAction(code=test_code)
  610. logger.info(action_ipython, extra={'msg_type': 'ACTION'})
  611. obs = await runtime.run_action(action_ipython)
  612. assert isinstance(obs, IPythonRunCellObservation)
  613. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  614. if run_as_devin:
  615. assert 'opendevin' in obs.content
  616. else:
  617. assert 'root' in obs.content
  618. # print pwd
  619. test_code = 'import os; print(os.getcwd())'
  620. action_ipython = IPythonRunCellAction(code=test_code)
  621. logger.info(action_ipython, extra={'msg_type': 'ACTION'})
  622. obs = await runtime.run_action(action_ipython)
  623. assert isinstance(obs, IPythonRunCellObservation)
  624. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  625. assert (
  626. obs.content.strip()
  627. == '/workspace\n[Jupyter current working directory: /workspace]'
  628. )
  629. # write a file
  630. test_code = "with open('test.txt', 'w') as f: f.write('Hello, world!')"
  631. action_ipython = IPythonRunCellAction(code=test_code)
  632. logger.info(action_ipython, extra={'msg_type': 'ACTION'})
  633. obs = await runtime.run_action(action_ipython)
  634. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  635. assert isinstance(obs, IPythonRunCellObservation)
  636. assert (
  637. obs.content.strip()
  638. == '[Code executed successfully with no output]\n[Jupyter current working directory: /workspace]'
  639. )
  640. # check file owner via bash
  641. action = CmdRunAction(command='ls -alh test.txt')
  642. logger.info(action, extra={'msg_type': 'ACTION'})
  643. obs = await runtime.run_action(action)
  644. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  645. assert obs.exit_code == 0
  646. if run_as_devin:
  647. # -rw-r--r-- 1 opendevin root 13 Jul 28 03:53 test.txt
  648. assert 'opendevin' in obs.content.split('\r\n')[0]
  649. assert 'root' in obs.content.split('\r\n')[0]
  650. else:
  651. # -rw-r--r-- 1 root root 13 Jul 28 03:53 test.txt
  652. assert 'root' in obs.content.split('\r\n')[0]
  653. # clean up
  654. action = CmdRunAction(command='rm -rf test')
  655. logger.info(action, extra={'msg_type': 'ACTION'})
  656. obs = await runtime.run_action(action)
  657. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  658. assert obs.exit_code == 0
  659. await runtime.close()
  660. await asyncio.sleep(1)
  661. @pytest.mark.asyncio
  662. async def test_ipython_simple(temp_dir, box_class):
  663. runtime = await _load_runtime(temp_dir, box_class)
  664. # Test run ipython
  665. # get username
  666. test_code = 'print(1)'
  667. action_ipython = IPythonRunCellAction(code=test_code)
  668. logger.info(action_ipython, extra={'msg_type': 'ACTION'})
  669. obs = await runtime.run_action(action_ipython)
  670. assert isinstance(obs, IPythonRunCellObservation)
  671. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  672. assert obs.content.strip() == '1\n[Jupyter current working directory: /workspace]'
  673. await runtime.close()
  674. await asyncio.sleep(1)
  675. async def _test_ipython_agentskills_fileop_pwd_impl(
  676. runtime: EventStreamRuntime, enable_auto_lint: bool
  677. ):
  678. # remove everything in /workspace
  679. action = CmdRunAction(command='rm -rf /workspace/*')
  680. logger.info(action, extra={'msg_type': 'ACTION'})
  681. obs = await runtime.run_action(action)
  682. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  683. assert obs.exit_code == 0
  684. action = CmdRunAction(command='mkdir test')
  685. logger.info(action, extra={'msg_type': 'ACTION'})
  686. obs = await runtime.run_action(action)
  687. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  688. assert isinstance(obs, CmdOutputObservation)
  689. assert obs.exit_code == 0
  690. action = IPythonRunCellAction(code="create_file('hello.py')")
  691. logger.info(action, extra={'msg_type': 'ACTION'})
  692. obs = await runtime.run_action(action)
  693. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  694. assert isinstance(obs, IPythonRunCellObservation)
  695. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  696. '[File: /workspace/hello.py (1 lines total)]\n'
  697. '(this is the beginning of the file)\n'
  698. '1|\n'
  699. '(this is the end of the file)\n'
  700. '[File hello.py created.]\n'
  701. '[Jupyter current working directory: /workspace]'
  702. ).strip().split('\n')
  703. action = CmdRunAction(command='cd test')
  704. logger.info(action, extra={'msg_type': 'ACTION'})
  705. obs = await runtime.run_action(action)
  706. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  707. assert isinstance(obs, CmdOutputObservation)
  708. assert obs.exit_code == 0
  709. # This should create a file in the current working directory
  710. # i.e., /workspace/test/hello.py instead of /workspace/hello.py
  711. action = IPythonRunCellAction(code="create_file('hello.py')")
  712. logger.info(action, extra={'msg_type': 'ACTION'})
  713. obs = await runtime.run_action(action)
  714. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  715. assert isinstance(obs, IPythonRunCellObservation)
  716. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  717. '[File: /workspace/test/hello.py (1 lines total)]\n'
  718. '(this is the beginning of the file)\n'
  719. '1|\n'
  720. '(this is the end of the file)\n'
  721. '[File hello.py created.]\n'
  722. '[Jupyter current working directory: /workspace/test]'
  723. ).strip().split('\n')
  724. if enable_auto_lint:
  725. # edit file, but make a mistake in indentation
  726. action = IPythonRunCellAction(
  727. code="insert_content_at_line('hello.py', 1, ' print(\"hello world\")')"
  728. )
  729. logger.info(action, extra={'msg_type': 'ACTION'})
  730. obs = await runtime.run_action(action)
  731. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  732. assert isinstance(obs, IPythonRunCellObservation)
  733. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  734. """
  735. [Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]
  736. ERRORS:
  737. /workspace/test/hello.py:1:3: E999 IndentationError: unexpected indent
  738. [This is how your edit would have looked if applied]
  739. -------------------------------------------------
  740. (this is the beginning of the file)
  741. 1| print("hello world")
  742. (this is the end of the file)
  743. -------------------------------------------------
  744. [This is the original code before your edit]
  745. -------------------------------------------------
  746. (this is the beginning of the file)
  747. 1|
  748. (this is the end of the file)
  749. -------------------------------------------------
  750. Your changes have NOT been applied. Please fix your edit command and try again.
  751. You either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.
  752. DO NOT re-run the same failed edit command. Running it again will lead to the same error.
  753. [Jupyter current working directory: /workspace/test]
  754. """
  755. ).strip().split('\n')
  756. # edit file with correct indentation
  757. action = IPythonRunCellAction(
  758. code="insert_content_at_line('hello.py', 1, 'print(\"hello world\")')"
  759. )
  760. logger.info(action, extra={'msg_type': 'ACTION'})
  761. obs = await runtime.run_action(action)
  762. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  763. assert isinstance(obs, IPythonRunCellObservation)
  764. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  765. """
  766. [File: /workspace/test/hello.py (1 lines total after edit)]
  767. (this is the beginning of the file)
  768. 1|print("hello world")
  769. (this is the end of the file)
  770. [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.]
  771. [Jupyter current working directory: /workspace/test]
  772. """
  773. ).strip().split('\n')
  774. action = CmdRunAction(command='rm -rf /workspace/*')
  775. logger.info(action, extra={'msg_type': 'ACTION'})
  776. obs = await runtime.run_action(action)
  777. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  778. assert obs.exit_code == 0
  779. await runtime.close()
  780. await asyncio.sleep(1)
  781. @pytest.mark.asyncio
  782. async def test_ipython_agentskills_fileop_pwd(
  783. temp_dir, box_class, run_as_devin, enable_auto_lint
  784. ):
  785. """Make sure that cd in bash also update the current working directory in ipython."""
  786. runtime = await _load_runtime(
  787. temp_dir, box_class, run_as_devin, enable_auto_lint=enable_auto_lint
  788. )
  789. await _test_ipython_agentskills_fileop_pwd_impl(runtime, enable_auto_lint)
  790. await runtime.close()
  791. await asyncio.sleep(1)
  792. @pytest.mark.asyncio
  793. async def test_ipython_agentskills_fileop_pwd_with_userdir(temp_dir, box_class):
  794. """Make sure that cd in bash also update the current working directory in ipython.
  795. Handle special case where the pwd is provided as "~", which should be expanded using os.path.expanduser
  796. on the client side.
  797. """
  798. runtime = await _load_runtime(
  799. temp_dir,
  800. box_class,
  801. run_as_devin=False,
  802. )
  803. action = CmdRunAction(command='cd ~')
  804. logger.info(action, extra={'msg_type': 'ACTION'})
  805. obs = await runtime.run_action(action)
  806. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  807. assert obs.exit_code == 0
  808. action = CmdRunAction(command='mkdir test && ls -la')
  809. logger.info(action, extra={'msg_type': 'ACTION'})
  810. obs = await runtime.run_action(action)
  811. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  812. assert isinstance(obs, CmdOutputObservation)
  813. assert obs.exit_code == 0
  814. action = IPythonRunCellAction(code="create_file('hello.py')")
  815. logger.info(action, extra={'msg_type': 'ACTION'})
  816. obs = await runtime.run_action(action)
  817. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  818. assert isinstance(obs, IPythonRunCellObservation)
  819. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  820. '[File: /root/hello.py (1 lines total)]\n'
  821. '(this is the beginning of the file)\n'
  822. '1|\n'
  823. '(this is the end of the file)\n'
  824. '[File hello.py created.]\n'
  825. '[Jupyter current working directory: /root]'
  826. ).strip().split('\n')
  827. action = CmdRunAction(command='cd test')
  828. logger.info(action, extra={'msg_type': 'ACTION'})
  829. obs = await runtime.run_action(action)
  830. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  831. assert isinstance(obs, CmdOutputObservation)
  832. assert obs.exit_code == 0
  833. # This should create a file in the current working directory
  834. # i.e., /workspace/test/hello.py instead of /workspace/hello.py
  835. action = IPythonRunCellAction(code="create_file('hello.py')")
  836. logger.info(action, extra={'msg_type': 'ACTION'})
  837. obs = await runtime.run_action(action)
  838. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  839. assert isinstance(obs, IPythonRunCellObservation)
  840. assert obs.content.replace('\r\n', '\n').strip().split('\n') == (
  841. '[File: /root/test/hello.py (1 lines total)]\n'
  842. '(this is the beginning of the file)\n'
  843. '1|\n'
  844. '(this is the end of the file)\n'
  845. '[File hello.py created.]\n'
  846. '[Jupyter current working directory: /root/test]'
  847. ).strip().split('\n')
  848. await runtime.close()
  849. await asyncio.sleep(1)
  850. @pytest.mark.asyncio
  851. async def test_bash_python_version(temp_dir, box_class):
  852. """Make sure Python is available in bash."""
  853. runtime = await _load_runtime(temp_dir, box_class)
  854. action = CmdRunAction(command='which python')
  855. logger.info(action, extra={'msg_type': 'ACTION'})
  856. obs = await runtime.run_action(action)
  857. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  858. assert obs.exit_code == 0
  859. action = CmdRunAction(command='python --version')
  860. logger.info(action, extra={'msg_type': 'ACTION'})
  861. obs = await runtime.run_action(action)
  862. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  863. assert obs.exit_code == 0
  864. # Should not error out
  865. action = CmdRunAction(command='pip --version')
  866. logger.info(action, extra={'msg_type': 'ACTION'})
  867. obs = await runtime.run_action(action)
  868. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  869. assert obs.exit_code == 0
  870. # Should not error out
  871. await runtime.close()
  872. await asyncio.sleep(1)
  873. @pytest.mark.asyncio
  874. async def test_ipython_package_install(temp_dir, box_class, run_as_devin):
  875. """Make sure that cd in bash also update the current working directory in ipython."""
  876. runtime = await _load_runtime(temp_dir, box_class, run_as_devin)
  877. # It should error out since pymsgbox is not installed
  878. action = IPythonRunCellAction(code='import pymsgbox')
  879. logger.info(action, extra={'msg_type': 'ACTION'})
  880. obs = await runtime.run_action(action)
  881. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  882. assert "ModuleNotFoundError: No module named 'pymsgbox'" in obs.content
  883. # Install pymsgbox in Jupyter
  884. action = IPythonRunCellAction(code='%pip install pymsgbox==1.0.9')
  885. logger.info(action, extra={'msg_type': 'ACTION'})
  886. obs = await runtime.run_action(action)
  887. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  888. assert (
  889. 'Successfully installed pymsgbox-1.0.9' in obs.content
  890. or '[Package installed successfully]' in obs.content
  891. )
  892. action = IPythonRunCellAction(code='import pymsgbox')
  893. logger.info(action, extra={'msg_type': 'ACTION'})
  894. obs = await runtime.run_action(action)
  895. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  896. # import should not error out
  897. assert (
  898. obs.content.strip()
  899. == '[Code executed successfully with no output]\n[Jupyter current working directory: /workspace]'
  900. )
  901. await runtime.close()
  902. await asyncio.sleep(1)
  903. def _create_test_file(host_temp_dir):
  904. # Single file
  905. with open(os.path.join(host_temp_dir, 'test_file.txt'), 'w') as f:
  906. f.write('Hello, World!')
  907. @pytest.mark.asyncio
  908. async def test_copy_single_file(temp_dir, box_class):
  909. runtime = await _load_runtime(temp_dir, box_class)
  910. with tempfile.TemporaryDirectory() as host_temp_dir:
  911. _create_test_file(host_temp_dir)
  912. await runtime.copy_to(
  913. os.path.join(host_temp_dir, 'test_file.txt'), '/workspace'
  914. )
  915. action = CmdRunAction(command='ls -alh /workspace')
  916. logger.info(action, extra={'msg_type': 'ACTION'})
  917. obs = await runtime.run_action(action)
  918. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  919. assert isinstance(obs, CmdOutputObservation)
  920. assert obs.exit_code == 0
  921. assert 'test_file.txt' in obs.content
  922. action = CmdRunAction(command='cat /workspace/test_file.txt')
  923. logger.info(action, extra={'msg_type': 'ACTION'})
  924. obs = await runtime.run_action(action)
  925. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  926. assert isinstance(obs, CmdOutputObservation)
  927. assert obs.exit_code == 0
  928. assert 'Hello, World!' in obs.content
  929. await runtime.close()
  930. await asyncio.sleep(1)
  931. def _create_test_dir_with_files(host_temp_dir):
  932. os.mkdir(os.path.join(host_temp_dir, 'test_dir'))
  933. with open(os.path.join(host_temp_dir, 'test_dir', 'file1.txt'), 'w') as f:
  934. f.write('File 1 content')
  935. with open(os.path.join(host_temp_dir, 'test_dir', 'file2.txt'), 'w') as f:
  936. f.write('File 2 content')
  937. @pytest.mark.asyncio
  938. async def test_copy_directory_recursively(temp_dir, box_class):
  939. runtime = await _load_runtime(temp_dir, box_class)
  940. with tempfile.TemporaryDirectory() as host_temp_dir:
  941. # We need a separate directory, since temp_dir is mounted to /workspace
  942. _create_test_dir_with_files(host_temp_dir)
  943. await runtime.copy_to(
  944. os.path.join(host_temp_dir, 'test_dir'), '/workspace', recursive=True
  945. )
  946. action = CmdRunAction(command='ls -alh /workspace')
  947. logger.info(action, extra={'msg_type': 'ACTION'})
  948. obs = await runtime.run_action(action)
  949. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  950. assert isinstance(obs, CmdOutputObservation)
  951. assert obs.exit_code == 0
  952. assert 'test_dir' in obs.content
  953. assert 'file1.txt' not in obs.content
  954. assert 'file2.txt' not in obs.content
  955. action = CmdRunAction(command='ls -alh /workspace/test_dir')
  956. logger.info(action, extra={'msg_type': 'ACTION'})
  957. obs = await runtime.run_action(action)
  958. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  959. assert isinstance(obs, CmdOutputObservation)
  960. assert obs.exit_code == 0
  961. assert 'file1.txt' in obs.content
  962. assert 'file2.txt' in obs.content
  963. action = CmdRunAction(command='cat /workspace/test_dir/file1.txt')
  964. logger.info(action, extra={'msg_type': 'ACTION'})
  965. obs = await runtime.run_action(action)
  966. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  967. assert isinstance(obs, CmdOutputObservation)
  968. assert obs.exit_code == 0
  969. assert 'File 1 content' in obs.content
  970. await runtime.close()
  971. await asyncio.sleep(1)
  972. @pytest.mark.asyncio
  973. async def test_copy_to_non_existent_directory(temp_dir, box_class):
  974. runtime = await _load_runtime(temp_dir, box_class)
  975. with tempfile.TemporaryDirectory() as host_temp_dir:
  976. _create_test_file(host_temp_dir)
  977. await runtime.copy_to(
  978. os.path.join(host_temp_dir, 'test_file.txt'), '/workspace/new_dir'
  979. )
  980. action = CmdRunAction(command='cat /workspace/new_dir/test_file.txt')
  981. logger.info(action, extra={'msg_type': 'ACTION'})
  982. obs = await runtime.run_action(action)
  983. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  984. assert isinstance(obs, CmdOutputObservation)
  985. assert obs.exit_code == 0
  986. assert 'Hello, World!' in obs.content
  987. await runtime.close()
  988. await asyncio.sleep(1)
  989. @pytest.mark.asyncio
  990. async def test_overwrite_existing_file(temp_dir, box_class):
  991. runtime = await _load_runtime(temp_dir, box_class)
  992. # touch a file in /workspace
  993. action = CmdRunAction(command='touch /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. action = CmdRunAction(command='cat /workspace/test_file.txt')
  1000. logger.info(action, extra={'msg_type': 'ACTION'})
  1001. obs = await runtime.run_action(action)
  1002. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1003. assert isinstance(obs, CmdOutputObservation)
  1004. assert obs.exit_code == 0
  1005. assert 'Hello, World!' not in obs.content
  1006. with tempfile.TemporaryDirectory() as host_temp_dir:
  1007. _create_test_file(host_temp_dir)
  1008. await runtime.copy_to(
  1009. os.path.join(host_temp_dir, 'test_file.txt'), '/workspace'
  1010. )
  1011. action = CmdRunAction(command='cat /workspace/test_file.txt')
  1012. logger.info(action, extra={'msg_type': 'ACTION'})
  1013. obs = await runtime.run_action(action)
  1014. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1015. assert isinstance(obs, CmdOutputObservation)
  1016. assert obs.exit_code == 0
  1017. assert 'Hello, World!' in obs.content
  1018. await runtime.close()
  1019. await asyncio.sleep(1)
  1020. @pytest.mark.asyncio
  1021. async def test_copy_non_existent_file(temp_dir, box_class):
  1022. runtime = await _load_runtime(temp_dir, box_class)
  1023. with pytest.raises(FileNotFoundError):
  1024. await runtime.copy_to(
  1025. os.path.join(temp_dir, 'non_existent_file.txt'),
  1026. '/workspace/should_not_exist.txt',
  1027. )
  1028. action = CmdRunAction(command='ls /workspace/should_not_exist.txt')
  1029. logger.info(action, extra={'msg_type': 'ACTION'})
  1030. obs = await runtime.run_action(action)
  1031. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1032. assert isinstance(obs, CmdOutputObservation)
  1033. assert obs.exit_code != 0 # File should not exist
  1034. await runtime.close()
  1035. await asyncio.sleep(1)
  1036. @pytest.mark.asyncio
  1037. async def test_keep_prompt(temp_dir):
  1038. # only EventStreamRuntime supports keep_prompt
  1039. runtime = await _load_runtime(
  1040. temp_dir, box_class=EventStreamRuntime, run_as_devin=False
  1041. )
  1042. action = CmdRunAction(command='touch /workspace/test_file.txt')
  1043. logger.info(action, extra={'msg_type': 'ACTION'})
  1044. obs = await runtime.run_action(action)
  1045. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1046. assert isinstance(obs, CmdOutputObservation)
  1047. assert obs.exit_code == 0
  1048. assert 'root@' in obs.content
  1049. action = CmdRunAction(command='cat /workspace/test_file.txt', keep_prompt=False)
  1050. logger.info(action, extra={'msg_type': 'ACTION'})
  1051. obs = await runtime.run_action(action)
  1052. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1053. assert isinstance(obs, CmdOutputObservation)
  1054. assert obs.exit_code == 0
  1055. assert 'root@' not in obs.content
  1056. await runtime.close()
  1057. await asyncio.sleep(1)
  1058. @pytest.mark.asyncio
  1059. async def test_git_operation(box_class):
  1060. # do not mount workspace, since workspace mount by tests will be owned by root
  1061. # while the user_id we get via os.getuid() is different from root
  1062. # which causes permission issues
  1063. runtime = await _load_runtime(
  1064. temp_dir=None,
  1065. box_class=box_class,
  1066. # Need to use non-root user to expose issues
  1067. run_as_devin=True,
  1068. )
  1069. # this will happen if permission of runtime is not properly configured
  1070. # fatal: detected dubious ownership in repository at '/workspace'
  1071. # check the ownership of the current directory
  1072. action = CmdRunAction(command='ls -alh .')
  1073. logger.info(action, extra={'msg_type': 'ACTION'})
  1074. obs = await runtime.run_action(action)
  1075. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1076. assert isinstance(obs, CmdOutputObservation)
  1077. assert obs.exit_code == 0
  1078. # drwx--S--- 2 opendevin root 64 Aug 7 23:32 .
  1079. # drwxr-xr-x 1 root root 4.0K Aug 7 23:33 ..
  1080. for line in obs.content.split('\r\n'):
  1081. if ' ..' in line:
  1082. # parent directory should be owned by root
  1083. assert 'root' in line
  1084. assert 'opendevin' not in line
  1085. elif ' .' in line:
  1086. # current directory should be owned by opendevin
  1087. # and its group should be root
  1088. assert 'opendevin' in line
  1089. assert 'root' in line
  1090. # make sure all git operations are allowed
  1091. action = CmdRunAction(command='git init')
  1092. logger.info(action, extra={'msg_type': 'ACTION'})
  1093. obs = await runtime.run_action(action)
  1094. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1095. assert isinstance(obs, CmdOutputObservation)
  1096. assert obs.exit_code == 0
  1097. # create a file
  1098. action = CmdRunAction(command='echo "hello" > test_file.txt')
  1099. logger.info(action, extra={'msg_type': 'ACTION'})
  1100. obs = await runtime.run_action(action)
  1101. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1102. assert isinstance(obs, CmdOutputObservation)
  1103. assert obs.exit_code == 0
  1104. # git add
  1105. action = CmdRunAction(command='git add test_file.txt')
  1106. logger.info(action, extra={'msg_type': 'ACTION'})
  1107. obs = await runtime.run_action(action)
  1108. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1109. assert isinstance(obs, CmdOutputObservation)
  1110. assert obs.exit_code == 0
  1111. # git diff
  1112. action = CmdRunAction(command='git diff')
  1113. logger.info(action, extra={'msg_type': 'ACTION'})
  1114. obs = await runtime.run_action(action)
  1115. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1116. assert isinstance(obs, CmdOutputObservation)
  1117. assert obs.exit_code == 0
  1118. # git commit
  1119. action = CmdRunAction(command='git commit -m "test commit"')
  1120. logger.info(action, extra={'msg_type': 'ACTION'})
  1121. obs = await runtime.run_action(action)
  1122. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  1123. assert isinstance(obs, CmdOutputObservation)
  1124. assert obs.exit_code == 0
  1125. await runtime.close()
  1126. await runtime.close()
  1127. await asyncio.sleep(1)