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66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
"""Bash-related tests for the DockerRuntime, which connects to the ActionExecutor running in the sandbox."""

import os
import sys
import time
from pathlib import Path

import pytest
from conftest import (
    _close_test_runtime,
    _load_runtime,
)

from openhands.core.logger import openhands_logger as logger
from openhands.events.action import CmdRunAction
from openhands.events.observation import CmdOutputObservation, ErrorObservation
from openhands.runtime.impl.cli.cli_runtime import CLIRuntime
from openhands.runtime.impl.local.local_runtime import LocalRuntime
from openhands.runtime.utils.bash_constants import TIMEOUT_MESSAGE_TEMPLATE


def get_timeout_suffix(timeout_seconds):
    """Helper function to generate the expected timeout suffix."""
    return (
        f'[The command timed out after {timeout_seconds} seconds. '
        f'{TIMEOUT_MESSAGE_TEMPLATE}]'
    )


# ============================================================================================================================
# Bash-specific tests
# ============================================================================================================================


# Helper function to determine if running on Windows
def is_windows():
    return sys.platform == 'win32'


def _run_cmd_action(runtime, custom_command: str):
    action = CmdRunAction(command=custom_command)
    logger.info(action, extra={'msg_type': 'ACTION'})
    obs = runtime.run_action(action)
    assert isinstance(obs, (CmdOutputObservation, ErrorObservation))
    logger.info(obs, extra={'msg_type': 'OBSERVATION'})
    return obs


# Get platform-appropriate command
def get_platform_command(linux_cmd, windows_cmd):
    return windows_cmd if is_windows() else linux_cmd


def test_bash_server(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # Use python -u for unbuffered output, potentially helping capture initial output on Windows
        action = CmdRunAction(command='python -u -m http.server 8081')
        action.set_hard_timeout(1)
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert isinstance(obs, CmdOutputObservation)
        assert obs.exit_code == -1
        assert 'Serving HTTP on' in obs.content

        if runtime_cls == CLIRuntime:
            assert '[The command timed out after 1.0 seconds.]' in obs.metadata.suffix
        else:
            assert get_timeout_suffix(1.0) in obs.metadata.suffix

        action = CmdRunAction(command='C-c', is_input=True)
        action.set_hard_timeout(30)
        obs_interrupt = runtime.run_action(action)
        logger.info(obs_interrupt, extra={'msg_type': 'OBSERVATION'})

        if runtime_cls == CLIRuntime:
            assert isinstance(obs_interrupt, ErrorObservation)
            assert (
                "CLIRuntime does not support interactive input from the agent (e.g., 'C-c'). The command 'C-c' was not sent to any process."
                in obs_interrupt.content
            )
            assert obs_interrupt.error_id == 'AGENT_ERROR$BAD_ACTION'
        else:
            assert isinstance(obs_interrupt, CmdOutputObservation)
            assert obs_interrupt.exit_code == 0
            if not is_windows():
                # Linux/macOS behavior
                assert 'Keyboard interrupt received, exiting.' in obs_interrupt.content
                assert (
                    config.workspace_mount_path_in_sandbox
                    in obs_interrupt.metadata.working_dir
                )

        # Verify the server is actually stopped by trying to start another one
        # on the same port (regardless of OS)
        action = CmdRunAction(command='ls')
        action.set_hard_timeout(1)
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert isinstance(obs, CmdOutputObservation)
        assert obs.exit_code == 0
        # Check that the interrupt message is NOT present in subsequent output
        assert 'Keyboard interrupt received, exiting.' not in obs.content
        # Check working directory remains correct after interrupt handling
        if runtime_cls == CLIRuntime:
            # For CLIRuntime, working_dir is the absolute host path
            assert obs.metadata.working_dir == config.workspace_base
        else:
            # For other runtimes (e.g., Docker), it's relative to or contains the sandbox path
            assert config.workspace_mount_path_in_sandbox in obs.metadata.working_dir

        # run it again!
        action = CmdRunAction(command='python -u -m http.server 8081')
        action.set_hard_timeout(1)
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert isinstance(obs, CmdOutputObservation)
        assert obs.exit_code == -1
        assert 'Serving HTTP on' in obs.content

    finally:
        _close_test_runtime(runtime)


def test_bash_background_server(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    server_port = 8081
    try:
        # Start the server, expect it to timeout (run in background manner)
        action = CmdRunAction(f'python3 -m http.server {server_port} &')
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert isinstance(obs, CmdOutputObservation)

        if runtime_cls == CLIRuntime:
            # The '&' does not detach cleanly; the PTY session remains active.
            # the main cmd ends, then the server may receive SIGHUP.
            assert obs.exit_code == 0

            # Give the server a moment to be ready
            time.sleep(1)

            # `curl --fail` exits non-zero if connection fails or server returns an error.
            # Use a short connect timeout as the server is expected to be down.
            curl_action = CmdRunAction(
                f'curl --fail --connect-timeout 1 http://localhost:{server_port}'
            )
            curl_obs = runtime.run_action(curl_action)
            logger.info(curl_obs, extra={'msg_type': 'OBSERVATION'})
            assert isinstance(curl_obs, CmdOutputObservation)
            assert curl_obs.exit_code != 0

            # Confirm with pkill (CLIRuntime is assumed non-Windows here).
            # pkill returns 1 if no processes were matched.
            kill_action = CmdRunAction('pkill -f "http.server"')
            kill_obs = runtime.run_action(kill_action)
            logger.info(kill_obs, extra={'msg_type': 'OBSERVATION'})
            assert isinstance(kill_obs, CmdOutputObservation)
            # For CLIRuntime, bash -c "cmd &" exits quickly, orphaning "cmd".
            # CLIRuntime's timeout tries to kill the already-exited bash -c.
            # The orphaned http.server continues running.
            # So, pkill should find and kill the server.
            assert kill_obs.exit_code == 0
        else:
            assert obs.exit_code == 0

            # Give the server a moment to be ready
            time.sleep(1)

            # Verify the server is running by curling it
            if is_windows():
                curl_action = CmdRunAction(
                    f'Invoke-WebRequest -Uri http://localhost:{server_port} -UseBasicParsing | Select-Object -ExpandProperty Content'
                )
            else:
                curl_action = CmdRunAction(f'curl http://localhost:{server_port}')
            curl_obs = runtime.run_action(curl_action)
            logger.info(curl_obs, extra={'msg_type': 'OBSERVATION'})
            assert isinstance(curl_obs, CmdOutputObservation)
            assert curl_obs.exit_code == 0
            # Check for content typical of python http.server directory listing
            assert 'Directory listing for' in curl_obs.content

            # Kill the server
            if is_windows():
                # This assumes PowerShell context if LocalRuntime is used on Windows.
                kill_action = CmdRunAction('Get-Job | Stop-Job')
            else:
                kill_action = CmdRunAction('pkill -f "http.server"')
            kill_obs = runtime.run_action(kill_action)
            logger.info(kill_obs, extra={'msg_type': 'OBSERVATION'})
            assert isinstance(kill_obs, CmdOutputObservation)
            assert kill_obs.exit_code == 0

    finally:
        _close_test_runtime(runtime)


def test_multiline_commands(temp_dir, runtime_cls):
    runtime, config = _load_runtime(temp_dir, runtime_cls)
    try:
        if is_windows():
            # Windows PowerShell version using backticks for line continuation
            obs = _run_cmd_action(runtime, 'Write-Output `\n "foo"')
            assert obs.exit_code == 0, 'The exit code should be 0.'
            assert 'foo' in obs.content

            # test multiline output
            obs = _run_cmd_action(runtime, 'Write-Output "hello`nworld"')
            assert obs.exit_code == 0, 'The exit code should be 0.'
            assert 'hello\nworld' in obs.content

            # test whitespace
            obs = _run_cmd_action(runtime, 'Write-Output "a`n`n`nz"')
            assert obs.exit_code == 0, 'The exit code should be 0.'
            assert '\n\n\n' in obs.content
        else:
            # Original Linux bash version
            # single multiline command
            obs = _run_cmd_action(runtime, 'echo \\\n -e "foo"')
            assert obs.exit_code == 0, 'The exit code should be 0.'
            assert 'foo' in obs.content

            # test multiline echo
            obs = _run_cmd_action(runtime, 'echo -e "hello\nworld"')
            assert obs.exit_code == 0, 'The exit code should be 0.'
            assert 'hello\nworld' in obs.content

            # test whitespace
            obs = _run_cmd_action(runtime, 'echo -e "a\\n\\n\\nz"')
            assert obs.exit_code == 0, 'The exit code should be 0.'
            assert '\n\n\n' in obs.content
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(), reason='Test relies on Linux bash-specific complex commands'
)
def test_complex_commands(temp_dir, runtime_cls, run_as_openhands):
    cmd = """count=0; tries=0; while [ $count -lt 3 ]; do result=$(echo "Heads"); tries=$((tries+1)); echo "Flip $tries: $result"; if [ "$result" = "Heads" ]; then count=$((count+1)); else count=0; fi; done; echo "Got 3 heads in a row after $tries flips!";"""

    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        obs = _run_cmd_action(runtime, cmd)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert obs.exit_code == 0, 'The exit code should be 0.'
        assert 'Got 3 heads in a row after 3 flips!' in obs.content

    finally:
        _close_test_runtime(runtime)


def test_no_ps2_in_output(temp_dir, runtime_cls, run_as_openhands):
    """Test that the PS2 sign is not added to the output of a multiline command."""
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        if is_windows():
            obs = _run_cmd_action(runtime, 'Write-Output "hello`nworld"')
        else:
            obs = _run_cmd_action(runtime, 'echo -e "hello\nworld"')
        assert obs.exit_code == 0, 'The exit code should be 0.'

        assert 'hello\nworld' in obs.content
        assert '>' not in obs.content
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(), reason='Test uses Linux-specific bash loops and sed commands'
)
def test_multiline_command_loop(temp_dir, runtime_cls):
    # https://github.com/All-Hands-AI/OpenHands/issues/3143
    init_cmd = """mkdir -p _modules && \
for month in {01..04}; do
    for day in {01..05}; do
        touch "_modules/2024-${month}-${day}-sample.md"
    done
done && echo "created files"
"""
    follow_up_cmd = """for file in _modules/*.md; do
    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/')
    mv "$file" "$new_date"
done && echo "success"
"""
    runtime, config = _load_runtime(temp_dir, runtime_cls)
    try:
        obs = _run_cmd_action(runtime, init_cmd)
        assert obs.exit_code == 0, 'The exit code should be 0.'
        assert 'created files' in obs.content

        obs = _run_cmd_action(runtime, follow_up_cmd)
        assert obs.exit_code == 0, 'The exit code should be 0.'
        assert 'success' in obs.content
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    os.getenv('TEST_RUNTIME') == 'cli',
    reason='CLIRuntime uses bash -c which handles newline-separated commands. This test expects rejection. See test_cliruntime_multiple_newline_commands.',
)
def test_multiple_multiline_commands(temp_dir, runtime_cls, run_as_openhands):
    if is_windows():
        cmds = [
            'Get-ChildItem',
            'Write-Output "hello`nworld"',
            """Write-Output "hello it's me\"""",
            """Write-Output `
    ('hello ' + `
    'world')""",
            """Write-Output 'hello\nworld\nare\nyou\nthere?'""",
            """Write-Output 'hello\nworld\nare\nyou\n\nthere?'""",
            """Write-Output 'hello\nworld "'""",  # Escape the trailing double quote
        ]
    else:
        cmds = [
            'ls -l',
            'echo -e "hello\nworld"',
            """echo -e "hello it's me\"""",
            """echo \\
    -e 'hello' \\
    world""",
            """echo -e 'hello\\nworld\\nare\\nyou\\nthere?'""",
            """echo -e 'hello\nworld\nare\nyou\n\nthere?'""",
            """echo -e 'hello\nworld "'""",
        ]
    joined_cmds = '\n'.join(cmds)

    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # First test that running multiple commands at once fails
        obs = _run_cmd_action(runtime, joined_cmds)
        assert isinstance(obs, ErrorObservation)
        assert 'Cannot execute multiple commands at once' in obs.content

        # Now run each command individually and verify they work
        results = []
        for cmd in cmds:
            obs = _run_cmd_action(runtime, cmd)
            assert isinstance(obs, CmdOutputObservation)
            assert obs.exit_code == 0
            results.append(obs.content)

        # Verify all expected outputs are present
        if is_windows():
            assert '.git_config' in results[0]  # Get-ChildItem
        else:
            assert 'total 0' in results[0]  # ls -l
        assert 'hello\nworld' in results[1]  # echo -e "hello\nworld"
        assert "hello it's me" in results[2]  # echo -e "hello it\'s me"
        assert 'hello world' in results[3]  # echo -e 'hello' world
        assert (
            'hello\nworld\nare\nyou\nthere?' in results[4]
        )  # echo -e 'hello\nworld\nare\nyou\nthere?'
        assert (
            'hello\nworld\nare\nyou\n\nthere?' in results[5]
        )  # echo -e with literal newlines
        assert 'hello\nworld "' in results[6]  # echo -e with quote
    finally:
        _close_test_runtime(runtime)


def test_cliruntime_multiple_newline_commands(temp_dir, run_as_openhands):
    # This test is specific to CLIRuntime
    runtime_cls = CLIRuntime
    if is_windows():
        # Minimal check for Windows if CLIRuntime were to support it robustly with PowerShell for this.
        # For now, this test primarily targets the bash -c behavior on non-Windows.
        pytest.skip(
            'CLIRuntime newline command test primarily for non-Windows bash behavior'
        )
        # cmds = [
        #     'Get-ChildItem -Name .git_config', # Simpler command
        #     'Write-Output "hello`nworld"'
        # ]
        # expected_outputs = ['.git_config', 'hello\nworld']
    else:
        cmds = [
            'echo "hello"',  # A command that will always work
            'echo -e "hello\nworld"',
            """echo -e "hello it's me\"""",
        ]
        expected_outputs = [
            'hello',  # Simple string output
            'hello\nworld',
            "hello it's me",
        ]  # Simplified expectations
    joined_cmds = '\n'.join(cmds)

    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        obs = _run_cmd_action(runtime, joined_cmds)
        assert isinstance(obs, CmdOutputObservation)
        assert obs.exit_code == 0
        # Check that parts of each command's expected output are present
        for expected_part in expected_outputs:
            assert expected_part in obs.content
    finally:
        _close_test_runtime(runtime)


def test_cmd_run(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        if is_windows():
            # Windows PowerShell version
            obs = _run_cmd_action(
                runtime, f'Get-ChildItem -Path {config.workspace_mount_path_in_sandbox}'
            )
            assert obs.exit_code == 0

            obs = _run_cmd_action(runtime, 'Get-ChildItem')
            assert obs.exit_code == 0

            obs = _run_cmd_action(runtime, 'New-Item -ItemType Directory -Path test')
            assert obs.exit_code == 0

            obs = _run_cmd_action(runtime, 'Get-ChildItem')
            assert obs.exit_code == 0
            assert 'test' in obs.content

            obs = _run_cmd_action(runtime, 'New-Item -ItemType File -Path test/foo.txt')
            assert obs.exit_code == 0

            obs = _run_cmd_action(runtime, 'Get-ChildItem test')
            assert obs.exit_code == 0
            assert 'foo.txt' in obs.content

            # clean up
            _run_cmd_action(runtime, 'Remove-Item -Recurse -Force test')
            assert obs.exit_code == 0
        else:
            # Unix version
            obs = _run_cmd_action(
                runtime, f'ls -l {config.workspace_mount_path_in_sandbox}'
            )
            assert obs.exit_code == 0

            obs = _run_cmd_action(runtime, 'ls -l')
            assert obs.exit_code == 0
            assert 'total 0' in obs.content

            obs = _run_cmd_action(runtime, 'mkdir test')
            assert obs.exit_code == 0

            obs = _run_cmd_action(runtime, 'ls -l')
            assert obs.exit_code == 0
            if (
                run_as_openhands
                and runtime_cls != CLIRuntime
                and runtime_cls != LocalRuntime
            ):
                assert 'openhands' in obs.content
            elif runtime_cls == LocalRuntime or runtime_cls == CLIRuntime:
                assert 'root' not in obs.content and 'openhands' not in obs.content
            else:
                assert 'root' in obs.content
            assert 'test' in obs.content

            obs = _run_cmd_action(runtime, 'touch test/foo.txt')
            assert obs.exit_code == 0

            obs = _run_cmd_action(runtime, 'ls -l test')
            assert obs.exit_code == 0
            assert 'foo.txt' in obs.content

            # clean up: this is needed, since CI will not be
            # run as root, and this test may leave a file
            # owned by root
            _run_cmd_action(runtime, 'rm -rf test')
            assert obs.exit_code == 0
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    sys.platform != 'win32' and os.getenv('TEST_RUNTIME') == 'cli',
    reason='CLIRuntime runs as the host user, so ~ is the host home. This test assumes a sandboxed user.',
)
def test_run_as_user_correct_home_dir(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        if is_windows():
            # Windows PowerShell version
            obs = _run_cmd_action(runtime, 'cd $HOME && Get-Location')
            assert obs.exit_code == 0
            # Check for Windows-style home paths
            if runtime_cls == LocalRuntime:
                assert (
                    os.getenv('USERPROFILE') in obs.content
                    or os.getenv('HOME') in obs.content
                )
            # For non-local runtime, we are less concerned with precise paths
        else:
            # Original Linux version
            obs = _run_cmd_action(runtime, 'cd ~ && pwd')
            assert obs.exit_code == 0
            if runtime_cls == LocalRuntime:
                assert os.getenv('HOME') in obs.content
            elif run_as_openhands:
                assert '/home/openhands' in obs.content
            else:
                assert '/root' in obs.content
    finally:
        _close_test_runtime(runtime)


def test_multi_cmd_run_in_single_line(temp_dir, runtime_cls):
    runtime, config = _load_runtime(temp_dir, runtime_cls)
    try:
        if is_windows():
            # Windows PowerShell version using semicolon
            obs = _run_cmd_action(runtime, 'Get-Location && Get-ChildItem')
            assert obs.exit_code == 0
            assert config.workspace_mount_path_in_sandbox in obs.content
            assert '.git_config' in obs.content
        else:
            # Original Linux version using &&
            obs = _run_cmd_action(runtime, 'pwd && ls -l')
            assert obs.exit_code == 0
            assert config.workspace_mount_path_in_sandbox in obs.content
            assert 'total 0' in obs.content
    finally:
        _close_test_runtime(runtime)


def test_stateful_cmd(temp_dir, runtime_cls):
    runtime, config = _load_runtime(temp_dir, runtime_cls)
    try:
        if is_windows():
            # Windows PowerShell version
            obs = _run_cmd_action(
                runtime, 'New-Item -ItemType Directory -Path test -Force'
            )
            assert obs.exit_code == 0, 'The exit code should be 0.'

            obs = _run_cmd_action(runtime, 'Set-Location test')
            assert obs.exit_code == 0, 'The exit code should be 0.'

            obs = _run_cmd_action(runtime, 'Get-Location')
            assert obs.exit_code == 0, 'The exit code should be 0.'
            # Account for both forward and backward slashes in path
            norm_path = config.workspace_mount_path_in_sandbox.replace(
                '\\', '/'
            ).replace('//', '/')
            test_path = f'{norm_path}/test'.replace('//', '/')
            assert test_path in obs.content.replace('\\', '/')
        else:
            # Original Linux version
            obs = _run_cmd_action(runtime, 'mkdir -p test')
            assert obs.exit_code == 0, 'The exit code should be 0.'

            if runtime_cls == CLIRuntime:
                # For CLIRuntime, test CWD change and command execution within a single action
                # as CWD is enforced in the workspace.
                obs = _run_cmd_action(runtime, 'cd test && pwd')
            else:
                # For other runtimes, test stateful CWD change across actions
                obs = _run_cmd_action(runtime, 'cd test')
                assert obs.exit_code == 0, 'The exit code should be 0 for cd test.'
                obs = _run_cmd_action(runtime, 'pwd')

            assert obs.exit_code == 0, (
                'The exit code for the pwd command (or combined command) should be 0.'
            )
            assert (
                f'{config.workspace_mount_path_in_sandbox}/test' in obs.content.strip()
            )
    finally:
        _close_test_runtime(runtime)


def test_failed_cmd(temp_dir, runtime_cls):
    runtime, config = _load_runtime(temp_dir, runtime_cls)
    try:
        obs = _run_cmd_action(runtime, 'non_existing_command')
        assert obs.exit_code != 0, 'The exit code should not be 0 for a failed command.'
    finally:
        _close_test_runtime(runtime)


def _create_test_file(host_temp_dir):
    # Single file
    with open(os.path.join(host_temp_dir, 'test_file.txt'), 'w') as f:
        f.write('Hello, World!')


def test_copy_single_file(temp_dir, runtime_cls):
    runtime, config = _load_runtime(temp_dir, runtime_cls)
    try:
        sandbox_dir = config.workspace_mount_path_in_sandbox
        sandbox_file = os.path.join(sandbox_dir, 'test_file.txt')
        _create_test_file(temp_dir)
        runtime.copy_to(os.path.join(temp_dir, 'test_file.txt'), sandbox_dir)

        if is_windows():
            obs = _run_cmd_action(runtime, f'Get-ChildItem -Path {sandbox_dir}')
            assert obs.exit_code == 0
            assert 'test_file.txt' in obs.content

            obs = _run_cmd_action(runtime, f'Get-Content {sandbox_file}')
            assert obs.exit_code == 0
            assert 'Hello, World!' in obs.content
        else:
            obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
            assert obs.exit_code == 0
            assert 'test_file.txt' in obs.content

            obs = _run_cmd_action(runtime, f'cat {sandbox_file}')
            assert obs.exit_code == 0
            assert 'Hello, World!' in obs.content
    finally:
        _close_test_runtime(runtime)


def _create_host_test_dir_with_files(test_dir):
    logger.debug(f'creating `{test_dir}`')
    if not os.path.isdir(test_dir):
        os.makedirs(test_dir, exist_ok=True)
    logger.debug('creating test files in `test_dir`')
    with open(os.path.join(test_dir, 'file1.txt'), 'w') as f:
        f.write('File 1 content')
    with open(os.path.join(test_dir, 'file2.txt'), 'w') as f:
        f.write('File 2 content')


def test_copy_directory_recursively(temp_dir, runtime_cls):
    runtime, config = _load_runtime(temp_dir, runtime_cls)

    sandbox_dir = config.workspace_mount_path_in_sandbox
    try:
        temp_dir_copy = os.path.join(temp_dir, 'test_dir')
        # We need a separate directory, since temp_dir is mounted to /workspace
        _create_host_test_dir_with_files(temp_dir_copy)

        runtime.copy_to(temp_dir_copy, sandbox_dir, recursive=True)

        if is_windows():
            obs = _run_cmd_action(runtime, f'Get-ChildItem -Path {sandbox_dir}')
            assert obs.exit_code == 0
            assert 'test_dir' in obs.content
            assert 'file1.txt' not in obs.content
            assert 'file2.txt' not in obs.content

            obs = _run_cmd_action(
                runtime, f'Get-ChildItem -Path {sandbox_dir}/test_dir'
            )
            assert obs.exit_code == 0
            assert 'file1.txt' in obs.content
            assert 'file2.txt' in obs.content

            obs = _run_cmd_action(
                runtime, f'Get-Content {sandbox_dir}/test_dir/file1.txt'
            )
            assert obs.exit_code == 0
            assert 'File 1 content' in obs.content
        else:
            obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
            assert obs.exit_code == 0
            assert 'test_dir' in obs.content
            assert 'file1.txt' not in obs.content
            assert 'file2.txt' not in obs.content

            obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}/test_dir')
            assert obs.exit_code == 0
            assert 'file1.txt' in obs.content
            assert 'file2.txt' in obs.content

            obs = _run_cmd_action(runtime, f'cat {sandbox_dir}/test_dir/file1.txt')
            assert obs.exit_code == 0
            assert 'File 1 content' in obs.content
    finally:
        _close_test_runtime(runtime)


def test_copy_to_non_existent_directory(temp_dir, runtime_cls):
    runtime, config = _load_runtime(temp_dir, runtime_cls)
    try:
        sandbox_dir = config.workspace_mount_path_in_sandbox
        _create_test_file(temp_dir)
        runtime.copy_to(
            os.path.join(temp_dir, 'test_file.txt'), f'{sandbox_dir}/new_dir'
        )

        obs = _run_cmd_action(runtime, f'cat {sandbox_dir}/new_dir/test_file.txt')
        assert obs.exit_code == 0
        assert 'Hello, World!' in obs.content
    finally:
        _close_test_runtime(runtime)


def test_overwrite_existing_file(temp_dir, runtime_cls):
    runtime, config = _load_runtime(temp_dir, runtime_cls)
    try:
        sandbox_dir = config.workspace_mount_path_in_sandbox
        sandbox_file = os.path.join(sandbox_dir, 'test_file.txt')

        if is_windows():
            # Check initial state
            obs = _run_cmd_action(runtime, f'Get-ChildItem -Path {sandbox_dir}')
            assert obs.exit_code == 0
            assert 'test_file.txt' not in obs.content

            # Create an empty file
            obs = _run_cmd_action(
                runtime, f'New-Item -ItemType File -Path {sandbox_file} -Force'
            )
            assert obs.exit_code == 0

            # Verify file exists and is empty
            obs = _run_cmd_action(runtime, f'Get-ChildItem -Path {sandbox_dir}')
            assert obs.exit_code == 0
            assert 'test_file.txt' in obs.content

            obs = _run_cmd_action(runtime, f'Get-Content {sandbox_file}')
            assert obs.exit_code == 0
            assert obs.content.strip() == ''  # Empty file
            assert 'Hello, World!' not in obs.content

            # Create host file and copy to overwrite
            _create_test_file(temp_dir)
            runtime.copy_to(os.path.join(temp_dir, 'test_file.txt'), sandbox_dir)

            # Verify file content is overwritten
            obs = _run_cmd_action(runtime, f'Get-Content {sandbox_file}')
            assert obs.exit_code == 0
            assert 'Hello, World!' in obs.content
        else:
            # Original Linux version
            obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
            assert obs.exit_code == 0
            assert 'test_file.txt' not in obs.content  # Check initial state

            obs = _run_cmd_action(runtime, f'touch {sandbox_file}')
            assert obs.exit_code == 0

            obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
            assert obs.exit_code == 0
            assert 'test_file.txt' in obs.content

            obs = _run_cmd_action(runtime, f'cat {sandbox_file}')
            assert obs.exit_code == 0
            assert obs.content.strip() == ''  # Empty file
            assert 'Hello, World!' not in obs.content

            _create_test_file(temp_dir)
            runtime.copy_to(os.path.join(temp_dir, 'test_file.txt'), sandbox_dir)

            obs = _run_cmd_action(runtime, f'cat {sandbox_file}')
            assert obs.exit_code == 0
            assert 'Hello, World!' in obs.content
    finally:
        _close_test_runtime(runtime)


def test_copy_non_existent_file(temp_dir, runtime_cls):
    runtime, config = _load_runtime(temp_dir, runtime_cls)
    try:
        sandbox_dir = config.workspace_mount_path_in_sandbox
        with pytest.raises(FileNotFoundError):
            runtime.copy_to(
                os.path.join(sandbox_dir, 'non_existent_file.txt'),
                f'{sandbox_dir}/should_not_exist.txt',
            )

        obs = _run_cmd_action(runtime, f'ls {sandbox_dir}/should_not_exist.txt')
        assert obs.exit_code != 0  # File should not exist
    finally:
        _close_test_runtime(runtime)


def test_copy_from_directory(temp_dir, runtime_cls):
    runtime, config = _load_runtime(temp_dir, runtime_cls)
    sandbox_dir = config.workspace_mount_path_in_sandbox
    try:
        temp_dir_copy = os.path.join(temp_dir, 'test_dir')
        # We need a separate directory, since temp_dir is mounted to /workspace
        _create_host_test_dir_with_files(temp_dir_copy)

        # Initial state
        runtime.copy_to(temp_dir_copy, sandbox_dir, recursive=True)

        path_to_copy_from = f'{sandbox_dir}/test_dir'
        result = runtime.copy_from(path=path_to_copy_from)

        # Result is returned as a path
        assert isinstance(result, Path)

        if result.exists() and not is_windows():
            result.unlink()
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(), reason='Test uses Linux-specific file permissions and sudo commands'
)
def test_git_operation(temp_dir, runtime_cls):
    # do not mount workspace, since workspace mount by tests will be owned by root
    # while the user_id we get via os.getuid() is different from root
    # which causes permission issues
    runtime, config = _load_runtime(
        temp_dir=temp_dir,
        use_workspace=False,
        runtime_cls=runtime_cls,
        # Need to use non-root user to expose issues
        run_as_openhands=True,
    )
    # this will happen if permission of runtime is not properly configured
    # fatal: detected dubious ownership in repository at config.workspace_mount_path_in_sandbox
    try:
        if runtime_cls != LocalRuntime and runtime_cls != CLIRuntime:
            # on local machine, permissionless sudo will probably not be available
            obs = _run_cmd_action(runtime, 'sudo chown -R openhands:root .')
            assert obs.exit_code == 0

        # check the ownership of the current directory
        obs = _run_cmd_action(runtime, 'ls -alh .')
        assert obs.exit_code == 0
        # drwx--S--- 2 openhands root   64 Aug  7 23:32 .
        # drwxr-xr-x 1 root      root 4.0K Aug  7 23:33 ..
        for line in obs.content.split('\n'):
            if runtime_cls == LocalRuntime or runtime_cls == CLIRuntime:
                continue  # skip these checks

            if ' ..' in line:
                # parent directory should be owned by root
                assert 'root' in line
                assert 'openhands' not in line
            elif ' .' in line:
                # current directory should be owned by openhands
                # and its group should be root
                assert 'openhands' in line
                assert 'root' in line

        # make sure all git operations are allowed
        obs = _run_cmd_action(runtime, 'git init')
        assert obs.exit_code == 0

        # create a file
        obs = _run_cmd_action(runtime, 'echo "hello" > test_file.txt')
        assert obs.exit_code == 0

        if runtime_cls == LocalRuntime or runtime_cls == CLIRuntime:
            # set git config author in CI only, not on local machine
            logger.info('Setting git config author')
            obs = _run_cmd_action(
                runtime,
                'git config user.name "openhands" && git config user.email "[email protected]"',
            )
            assert obs.exit_code == 0

            # Set up git config - list current settings (should be empty or just what was set)
            obs = _run_cmd_action(runtime, 'git config --list')
            assert obs.exit_code == 0

        # git add
        obs = _run_cmd_action(runtime, 'git add test_file.txt')
        assert obs.exit_code == 0

        # git diff
        obs = _run_cmd_action(runtime, 'git diff --no-color --cached')
        assert obs.exit_code == 0
        assert 'b/test_file.txt' in obs.content
        assert '+hello' in obs.content

        # git commit
        obs = _run_cmd_action(runtime, 'git commit -m "test commit"')
        assert obs.exit_code == 0
    finally:
        _close_test_runtime(runtime)


def test_python_version(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        obs = runtime.run_action(CmdRunAction(command='python --version'))

        assert isinstance(obs, CmdOutputObservation), (
            'The observation should be a CmdOutputObservation.'
        )
        assert obs.exit_code == 0, 'The exit code should be 0.'
        assert 'Python 3' in obs.content, 'The output should contain "Python 3".'
    finally:
        _close_test_runtime(runtime)


def test_pwd_property(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # Create a subdirectory and verify pwd updates
        obs = _run_cmd_action(runtime, 'mkdir -p random_dir')
        assert obs.exit_code == 0

        obs = _run_cmd_action(runtime, 'cd random_dir && pwd')
        assert obs.exit_code == 0
        assert 'random_dir' in obs.content
    finally:
        _close_test_runtime(runtime)


def test_basic_command(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        if is_windows():
            # Test simple command
            obs = _run_cmd_action(runtime, "Write-Output 'hello world'")
            assert 'hello world' in obs.content
            assert obs.exit_code == 0

            # Test command with error
            obs = _run_cmd_action(runtime, 'nonexistent_command')
            assert obs.exit_code != 0
            assert 'not recognized' in obs.content or 'command not found' in obs.content

            # Test command with special characters
            obs = _run_cmd_action(
                runtime, 'Write-Output "hello   world    with`nspecial  chars"'
            )
            assert 'hello   world    with\nspecial  chars' in obs.content
            assert obs.exit_code == 0

            # Test multiple commands in sequence
            obs = _run_cmd_action(
                runtime,
                'Write-Output "first" && Write-Output "second" && Write-Output "third"',
            )
            assert 'first' in obs.content
            assert 'second' in obs.content
            assert 'third' in obs.content
            assert obs.exit_code == 0
        else:
            # Original Linux version
            # Test simple command
            obs = _run_cmd_action(runtime, "echo 'hello world'")
            assert 'hello world' in obs.content
            assert obs.exit_code == 0

            # Test command with error
            obs = _run_cmd_action(runtime, 'nonexistent_command')
            assert obs.exit_code == 127
            assert 'nonexistent_command: command not found' in obs.content

            # Test command with special characters
            obs = _run_cmd_action(
                runtime, "echo 'hello   world    with\nspecial  chars'"
            )
            assert 'hello   world    with\nspecial  chars' in obs.content
            assert obs.exit_code == 0

            # Test multiple commands in sequence
            obs = _run_cmd_action(
                runtime, 'echo "first" && echo "second" && echo "third"'
            )
            assert 'first' in obs.content
            assert 'second' in obs.content
            assert 'third' in obs.content
            assert obs.exit_code == 0
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(), reason='Powershell does not support interactive commands'
)
@pytest.mark.skipif(
    os.getenv('TEST_RUNTIME') == 'cli',
    reason='CLIRuntime does not support interactive commands from the agent.',
)
def test_interactive_command(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(
        temp_dir,
        runtime_cls,
        run_as_openhands,
        runtime_startup_env_vars={'NO_CHANGE_TIMEOUT_SECONDS': '1'},
    )
    try:
        # Test interactive command
        action = CmdRunAction('read -p "Enter name: " name && echo "Hello $name"')
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        # This should trigger SOFT timeout, so no need to set hard timeout
        assert 'Enter name:' in obs.content
        assert '[The command has no new output after 1 seconds.' in obs.metadata.suffix

        action = CmdRunAction('John', is_input=True)
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert 'Hello John' in obs.content
        assert '[The command completed with exit code 0.]' in obs.metadata.suffix

        # Test multiline command input with here document
        action = CmdRunAction("""cat << EOF
line 1
line 2
EOF""")
        obs = runtime.run_action(action)
        assert 'line 1\nline 2' in obs.content
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert '[The command completed with exit code 0.]' in obs.metadata.suffix
        assert obs.exit_code == 0
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(),
    reason='Test relies on Linux-specific commands like seq and bash for loops',
)
def test_long_output(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # Generate a long output
        action = CmdRunAction('for i in $(seq 1 5000); do echo "Line $i"; done')
        action.set_hard_timeout(10)
        obs = runtime.run_action(action)
        assert obs.exit_code == 0
        assert 'Line 1' in obs.content
        assert 'Line 5000' in obs.content
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(),
    reason='Test relies on Linux-specific commands like seq and bash for loops',
)
@pytest.mark.skipif(
    os.getenv('TEST_RUNTIME') == 'cli',
    reason='CLIRuntime does not truncate command output.',
)
def test_long_output_exceed_history_limit(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # Generate a long output
        action = CmdRunAction('for i in $(seq 1 50000); do echo "Line $i"; done')
        action.set_hard_timeout(30)
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert obs.exit_code == 0
        assert 'Previous command outputs are truncated' in obs.metadata.prefix
        assert 'Line 40000' in obs.content
        assert 'Line 50000' in obs.content
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(), reason='Test uses Linux-specific temp directory and bash for loops'
)
def test_long_output_from_nested_directories(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # Create nested directories with many files
        setup_cmd = 'mkdir -p /tmp/test_dir && cd /tmp/test_dir && for i in $(seq 1 100); do mkdir -p "folder_$i"; for j in $(seq 1 100); do touch "folder_$i/file_$j.txt"; done; done'
        setup_action = CmdRunAction(setup_cmd.strip())
        setup_action.set_hard_timeout(60)
        obs = runtime.run_action(setup_action)
        assert obs.exit_code == 0

        # List the directory structure recursively
        action = CmdRunAction('ls -R /tmp/test_dir')
        action.set_hard_timeout(60)
        obs = runtime.run_action(action)
        assert obs.exit_code == 0

        # Verify output contains expected files
        assert 'folder_1' in obs.content
        assert 'file_1.txt' in obs.content
        assert 'folder_100' in obs.content
        assert 'file_100.txt' in obs.content
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(),
    reason='Test uses Linux-specific commands like find and grep with complex syntax',
)
def test_command_backslash(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # Create a file with the content "implemented_function"
        action = CmdRunAction(
            'mkdir -p /tmp/test_dir && echo "implemented_function" > /tmp/test_dir/file_1.txt'
        )
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert obs.exit_code == 0

        # Reproduce an issue we ran into during evaluation
        # find /workspace/sympy__sympy__1.0 -type f -exec grep -l "implemented_function" {} \;
        # find: missing argument to `-exec'
        # --> This is unexpected output due to incorrect escaping of \;
        # This tests for correct escaping of \;
        action = CmdRunAction(
            'find /tmp/test_dir -type f -exec grep -l "implemented_function" {} \\;'
        )
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert obs.exit_code == 0
        assert '/tmp/test_dir/file_1.txt' in obs.content
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(), reason='Test uses Linux-specific ps aux, awk, and grep commands'
)
@pytest.mark.skipif(
    os.getenv('TEST_RUNTIME') == 'cli',
    reason='CLIRuntime does not support interactive commands from the agent.',
)
def test_stress_long_output_with_soft_and_hard_timeout(
    temp_dir, runtime_cls, run_as_openhands
):
    runtime, config = _load_runtime(
        temp_dir,
        runtime_cls,
        run_as_openhands,
        runtime_startup_env_vars={'NO_CHANGE_TIMEOUT_SECONDS': '1'},
        docker_runtime_kwargs={
            'cpu_period': 100000,  # 100ms
            'cpu_quota': 100000,  # Can use 100ms out of each 100ms period (1 CPU)
            'mem_limit': '4G',  # 4 GB of memory
        },
    )
    try:
        # Run a command that generates long output multiple times
        for i in range(10):
            start_time = time.time()

            # Check tmux memory usage (in KB)
            mem_action = CmdRunAction(
                'ps aux | awk \'{printf "%8.1f KB  %s\\n", $6, $0}\' | sort -nr | grep "/usr/bin/tmux" | grep -v grep | awk \'{print $1}\''
            )
            mem_obs = runtime.run_action(mem_action)
            assert mem_obs.exit_code == 0
            logger.info(
                f'Tmux memory usage (iteration {i}): {mem_obs.content.strip()} KB'
            )

            # Check action_execution_server mem
            mem_action = CmdRunAction(
                'ps aux | awk \'{printf "%8.1f KB  %s\\n", $6, $0}\' | sort -nr | grep "action_execution_server" | grep "/openhands/poetry" | grep -v grep | awk \'{print $1}\''
            )
            mem_obs = runtime.run_action(mem_action)
            assert mem_obs.exit_code == 0
            logger.info(
                f'Action execution server memory usage (iteration {i}): {mem_obs.content.strip()} KB'
            )

            # Test soft timeout
            action = CmdRunAction(
                'read -p "Do you want to continue? [Y/n] " answer; if [[ $answer == "Y" ]]; then echo "Proceeding with operation..."; echo "Operation completed successfully!"; else echo "Operation cancelled."; exit 1; fi'
            )
            obs = runtime.run_action(action)
            assert 'Do you want to continue?' in obs.content
            assert obs.exit_code == -1  # Command is still running, waiting for input

            # Send the confirmation
            action = CmdRunAction('Y', is_input=True)
            obs = runtime.run_action(action)
            assert 'Proceeding with operation...' in obs.content
            assert 'Operation completed successfully!' in obs.content
            assert obs.exit_code == 0
            assert '[The command completed with exit code 0.]' in obs.metadata.suffix

            # Test hard timeout w/ long output
            # Generate long output with 1000 asterisks per line
            action = CmdRunAction(
                f'export i={i}; for j in $(seq 1 100); do echo "Line $j - Iteration $i - $(printf \'%1000s\' | tr " " "*")"; sleep 1; done'
            )
            action.set_hard_timeout(2)
            obs = runtime.run_action(action)

            # Verify the output
            assert obs.exit_code == -1
            assert f'Line 1 - Iteration {i}' in obs.content
            # assert f'Line 1000 - Iteration {i}' in obs.content
            # assert '[The command completed with exit code 0.]' in obs.metadata.suffix

            # Because hard-timeout is triggered, the terminal will in a weird state
            # where it will not accept any new commands.
            obs = runtime.run_action(CmdRunAction('ls'))
            assert obs.exit_code == -1
            assert 'The previous command is still running' in obs.metadata.suffix

            # We need to send a Ctrl+C to reset the terminal.
            obs = runtime.run_action(CmdRunAction('C-c', is_input=True))
            assert obs.exit_code == 130

            # Now make sure the terminal is in a good state
            obs = runtime.run_action(CmdRunAction('ls'))
            assert obs.exit_code == 0

            duration = time.time() - start_time
            logger.info(f'Completed iteration {i} in {duration:.2f} seconds')

    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    os.getenv('TEST_RUNTIME') == 'cli',
    reason='FIXME: CLIRuntime does not watch previously timed-out commands except for getting full output a short time after timeout.',
)
def test_command_output_continuation(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        if is_windows():
            # Windows PowerShell version
            action = CmdRunAction(
                '1..5 | ForEach-Object { Write-Output $_; Start-Sleep 3 }'
            )
            action.set_hard_timeout(2.5)
            obs = runtime.run_action(action)
            assert obs.content.strip() == '1'
            assert obs.metadata.prefix == ''
            assert '[The command timed out after 2.5 seconds.' in obs.metadata.suffix

            # Continue watching output
            action = CmdRunAction('')
            action.set_hard_timeout(2.5)
            obs = runtime.run_action(action)
            assert (
                '[Below is the output of the previous command.]' in obs.metadata.prefix
            )
            assert obs.content.strip() == '2'
            assert '[The command timed out after 2.5 seconds.' in obs.metadata.suffix

            # Continue until completion
            for expected in ['3', '4', '5']:
                action = CmdRunAction('')
                action.set_hard_timeout(2.5)
                obs = runtime.run_action(action)
                assert (
                    '[Below is the output of the previous command.]'
                    in obs.metadata.prefix
                )
                assert obs.content.strip() == expected
                assert (
                    '[The command timed out after 2.5 seconds.' in obs.metadata.suffix
                )

            # Final empty command to complete
            action = CmdRunAction('')
            obs = runtime.run_action(action)
            assert '[The command completed with exit code 0.]' in obs.metadata.suffix
        else:
            # Original Linux version
            # Start a command that produces output slowly
            action = CmdRunAction('for i in {1..5}; do echo $i; sleep 3; done')
            action.set_hard_timeout(2.5)
            obs = runtime.run_action(action)
            assert obs.content.strip() == '1'
            assert obs.metadata.prefix == ''
            assert '[The command timed out after 2.5 seconds.' in obs.metadata.suffix

            # Continue watching output
            action = CmdRunAction('')
            action.set_hard_timeout(2.5)
            obs = runtime.run_action(action)
            assert (
                '[Below is the output of the previous command.]' in obs.metadata.prefix
            )
            assert obs.content.strip() == '2'
            assert '[The command timed out after 2.5 seconds.' in obs.metadata.suffix

            # Continue until completion
            for expected in ['3', '4', '5']:
                action = CmdRunAction('')
                action.set_hard_timeout(2.5)
                obs = runtime.run_action(action)
                assert (
                    '[Below is the output of the previous command.]'
                    in obs.metadata.prefix
                )
                assert obs.content.strip() == expected
                assert (
                    '[The command timed out after 2.5 seconds.' in obs.metadata.suffix
                )

            # Final empty command to complete
            action = CmdRunAction('')
            obs = runtime.run_action(action)
            assert '[The command completed with exit code 0.]' in obs.metadata.suffix
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    os.getenv('TEST_RUNTIME') == 'cli',
    reason='FIXME: CLIRuntime does not implement empty command behavior.',
)
def test_long_running_command_follow_by_execute(
    temp_dir, runtime_cls, run_as_openhands
):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        if is_windows():
            action = CmdRunAction('1..3 | ForEach-Object { Write-Output $_; sleep 3 }')
        else:
            # Test command that produces output slowly
            action = CmdRunAction('for i in {1..3}; do echo $i; sleep 3; done')

        action.set_hard_timeout(2.5)
        obs = runtime.run_action(action)
        assert '1' in obs.content  # First number should appear before timeout
        assert obs.metadata.exit_code == -1  # -1 indicates command is still running
        assert '[The command timed out after 2.5 seconds.' in obs.metadata.suffix
        assert obs.metadata.prefix == ''

        # Continue watching output
        action = CmdRunAction('')
        action.set_hard_timeout(2.5)
        obs = runtime.run_action(action)
        assert '2' in obs.content
        assert obs.metadata.prefix == '[Below is the output of the previous command.]\n'
        assert '[The command timed out after 2.5 seconds.' in obs.metadata.suffix
        assert obs.metadata.exit_code == -1  # -1 indicates command is still running

        # Test command that produces no output
        action = CmdRunAction('sleep 15')
        action.set_hard_timeout(2.5)
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert '3' not in obs.content
        assert obs.metadata.prefix == '[Below is the output of the previous command.]\n'
        assert 'The previous command is still running' in obs.metadata.suffix
        assert obs.metadata.exit_code == -1  # -1 indicates command is still running

        # Finally continue again
        action = CmdRunAction('')
        obs = runtime.run_action(action)
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert '3' in obs.content
        assert '[The command completed with exit code 0.]' in obs.metadata.suffix
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    os.getenv('TEST_RUNTIME') == 'cli',
    reason='FIXME: CLIRuntime does not implement empty command behavior.',
)
def test_empty_command_errors(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # Test empty command without previous command - behavior should be the same on all platforms
        obs = runtime.run_action(CmdRunAction(''))
        assert isinstance(obs, CmdOutputObservation)
        assert (
            'ERROR: No previous running command to retrieve logs from.' in obs.content
        )
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(), reason='Powershell does not support interactive commands'
)
@pytest.mark.skipif(
    os.getenv('TEST_RUNTIME') == 'cli',
    reason='CLIRuntime does not support interactive commands from the agent.',
)
def test_python_interactive_input(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # Test Python program that asks for input - same for both platforms
        python_script = """name = input('Enter your name: '); age = input('Enter your age: '); print(f'Hello {name}, you are {age} years old')"""

        # Start Python with the interactive script
        # For both platforms we can use the same command
        obs = runtime.run_action(CmdRunAction(f'python -c "{python_script}"'))
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert 'Enter your name:' in obs.content
        assert obs.metadata.exit_code == -1  # -1 indicates command is still running

        # Send first input (name)
        obs = runtime.run_action(CmdRunAction('Alice', is_input=True))
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert 'Enter your age:' in obs.content
        assert obs.metadata.exit_code == -1

        # Send second input (age)
        obs = runtime.run_action(CmdRunAction('25', is_input=True))
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert 'Hello Alice, you are 25 years old' in obs.content
        assert obs.metadata.exit_code == 0
        assert '[The command completed with exit code 0.]' in obs.metadata.suffix
    finally:
        _close_test_runtime(runtime)


@pytest.mark.skipif(
    is_windows(), reason='Powershell does not support interactive commands'
)
@pytest.mark.skipif(
    os.getenv('TEST_RUNTIME') == 'cli',
    reason='CLIRuntime does not support interactive commands from the agent.',
)
def test_python_interactive_input_without_set_input(
    temp_dir, runtime_cls, run_as_openhands
):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # Test Python program that asks for input
        python_script = """name = input('Enter your name: '); age = input('Enter your age: '); print(f'Hello {name}, you are {age} years old')"""

        # Start Python with the interactive script
        obs = runtime.run_action(CmdRunAction(f'python -c "{python_script}"'))
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert 'Enter your name:' in obs.content
        assert obs.metadata.exit_code == -1  # -1 indicates command is still running

        # Send first input (name)
        obs = runtime.run_action(CmdRunAction('Alice', is_input=False))
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert 'Enter your age:' not in obs.content
        assert (
            'Your command "Alice" is NOT executed. The previous command is still running'
            in obs.metadata.suffix
        )
        assert obs.metadata.exit_code == -1

        # Try again now with input
        obs = runtime.run_action(CmdRunAction('Alice', is_input=True))
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert 'Enter your age:' in obs.content
        assert obs.metadata.exit_code == -1

        obs = runtime.run_action(CmdRunAction('25', is_input=True))
        logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert 'Hello Alice, you are 25 years old' in obs.content
        assert obs.metadata.exit_code == 0
        assert '[The command completed with exit code 0.]' in obs.metadata.suffix
    finally:
        _close_test_runtime(runtime)


def test_bash_remove_prefix(temp_dir, runtime_cls, run_as_openhands):
    runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
    try:
        # create a git repo - same for both platforms
        action = CmdRunAction(
            'git init && git remote add origin https://github.com/All-Hands-AI/OpenHands'
        )
        obs = runtime.run_action(action)
        # logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert obs.metadata.exit_code == 0

        # Check git remote - same for both platforms
        obs = runtime.run_action(CmdRunAction('git remote -v'))
        # logger.info(obs, extra={'msg_type': 'OBSERVATION'})
        assert obs.metadata.exit_code == 0
        assert 'https://github.com/All-Hands-AI/OpenHands' in obs.content
        assert 'git remote -v' not in obs.content
    finally:
        _close_test_runtime(runtime)