Repository navigation
Feat: add local & ssh provider in admin panel - #14995
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds SSH sandbox provider and paramiko; shifts provider resolution and config defaults to Admin settings and schemas; updates admin backend/UI for provider selection, config, and connection testing; makes sandbox client and executor provider-aware; adds tests, docs, and docker/.env updates. ChangesSandbox Provider System Expansion and Refactoring
Sequence Diagram(s)sequenceDiagram
participant AdminUI
participant AdminService
participant SandboxClient
participant SSHProvider
participant RemoteHost
AdminUI->>AdminService: set_config(provider_type="ssh", config)
AdminService->>SSHProvider: validate_config(config)
AdminService->>SandboxClient: reload_provider()
SandboxClient->>SSHProvider: initialize(config)
SSHProvider->>RemoteHost: _create_ssh_client() / health_check()
RemoteHost-->>SSHProvider: connected
SSHProvider-->>SandboxClient: initialized
AdminUI->>AdminService: test_connection()
AdminService->>SSHProvider: create_instance()
SSHProvider->>RemoteHost: create workspace
RemoteHost-->>SSHProvider: workspace path
AdminService->>SSHProvider: execute_code(test_program)
SSHProvider->>RemoteHost: upload script & run
RemoteHost-->>SSHProvider: stdout/stderr/exit_code, artifacts
SSHProvider-->>AdminService: ExecutionResult
AdminService->>SSHProvider: destroy_instance()
SSHProvider->>RemoteHost: cleanup workspace
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
test/unit_test/agent/sandbox/test_ssh_provider.py (1)
102-188: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick winAdd pytest priority markers to the new tests.
These new tests are missing required priority markers (for example,
@pytest.mark.p1/p2/p3) on each test function.Suggested update
+@pytest.mark.p2 def test_ssh_provider_initialize_requires_command_template(monkeypatch): @@ +@pytest.mark.p1 def test_ssh_provider_executes_python_main_and_collects_artifacts(monkeypatch): @@ +@pytest.mark.p1 def test_ssh_provider_propagates_timeouts():As per coding guidelines,
test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python backend tests.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit_test/agent/sandbox/test_ssh_provider.py` around lines 102 - 188, Add pytest priority markers to the three new test functions by decorating each with an appropriate marker (e.g., `@pytest.mark.p1` or p2/p3 as required): test_ssh_provider_initialize_requires_command_template, test_ssh_provider_executes_python_main_and_collects_artifacts, and test_ssh_provider_propagates_timeouts; ensure pytest is imported at the top of the file if not already, and place the decorator directly above each def so the tests carry the required priority metadata.test/unit_test/agent/sandbox/test_local_provider.py (1)
25-95: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick winMark these tests with pytest priority decorators.
The updated tests don’t include required priority markers (
p1/p2/p3).As per coding guidelines,
test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python backend tests.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit_test/agent/sandbox/test_local_provider.py` around lines 25 - 95, These tests are missing the required pytest priority markers; import pytest at the top of the file and add the appropriate priority decorators (e.g., `@pytest.mark.p1` or `@pytest.mark.p2/`@pytest.mark.p3 per guidelines) above each test function (test_local_provider_initializes_from_config, test_local_provider_executes_python_main, test_local_provider_collects_artifacts, test_local_provider_times_out) so they carry the required p1/p2/p3 markers; ensure you use the correct priority for each test per your test classification and that pytest.ini/registering of those markers exists in the repo.agent/sandbox/providers/local.py (1)
256-266:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winOutdated error messages reference removed environment variables.
The
_validate_limits()method still referencesSANDBOX_LOCAL_*environment variable names in error messages, but the provider no longer reads from environment variables. These messages should reflect the new config-driven approach.📝 Proposed fix for error messages
def _validate_limits(self) -> None: if self.timeout <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_TIMEOUT must be greater than 0.") + raise SandboxProviderConfigError("timeout must be greater than 0.") if self.max_memory_mb <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_MEMORY_MB must be greater than 0.") + raise SandboxProviderConfigError("max_memory_mb must be greater than 0.") if self.max_output_bytes <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_OUTPUT_BYTES must be greater than 0.") + raise SandboxProviderConfigError("max_output_bytes must be greater than 0.") if self.max_artifacts < 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_ARTIFACTS must be greater than or equal to 0.") + raise SandboxProviderConfigError("max_artifacts must be greater than or equal to 0.") if self.max_artifact_bytes <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_ARTIFACT_BYTES must be greater than 0.") + raise SandboxProviderConfigError("max_artifact_bytes must be greater than 0.")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/sandbox/providers/local.py` around lines 256 - 266, The error messages in _validate_limits() still reference removed environment variables; update each SandboxProviderConfigError raised inside the _validate_limits method to mention the provider config fields (e.g., "timeout", "max_memory_mb", "max_output_bytes", "max_artifacts", "max_artifact_bytes" or "sandbox provider configuration") and their required bounds instead of SANDBOX_LOCAL_* env var names so the exceptions reflect the config-driven approach; adjust messages in the _validate_limits function where SandboxProviderConfigError is raised to clearly state which config field is invalid and the expected constraint.
🧹 Nitpick comments (4)
agent/tools/code_exec.py (1)
371-377: 💤 Low valueConsider if reloading the provider on every code execution is necessary.
Calling
reload_provider()before each execution ensures configuration changes are picked up immediately, but may introduce overhead if code execution is frequent. If provider configuration changes are rare, consider caching/throttling the reload or only reloading when the configuration has actually changed.The logging addition at lines 374-377 follows coding guidelines.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/tools/code_exec.py` around lines 371 - 377, The call to reload_provider() before every execution is potentially expensive; change the code so reload_provider() is not unconditionally invoked on each run — instead implement a conditional reload or caching strategy: track provider configuration state (e.g., last_known_provider_config) and only call reload_provider() when get_provider_info() indicates a change, or throttle reloads (e.g., allow reload once per interval) before logging provider_type and calling logging.info(...) that uses provider_info.get("provider_type") and provider_type; update the logic around reload_provider(), get_provider_info(), provider_info and provider_type accordingly.agent/sandbox/providers/ssh.py (2)
438-438: 💤 Low valueSecurity concern:
AutoAddPolicyaccepts any SSH host key.Using
AutoAddPolicymakes the connection vulnerable to man-in-the-middle attacks, as it blindly trusts any host key presented. For a sandbox execution context where the target host is typically known and controlled, consider:
- Documenting this risk clearly in the config schema description for
host- Or providing an optional
host_keyconfig field for fingerprint verificationThis may be acceptable for internal/trusted networks, but should be acknowledged.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/sandbox/providers/ssh.py` at line 438, The code currently calls client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) which blindly accepts any host key; update the SSH provider (the connect/auth logic where set_missing_host_key_policy is called, e.g., in the SSH provider class or connect method) to support explicit host key verification: add an optional config field host_key (fingerprint or public key) to the provider schema and, if provided, use paramiko.RSAKey/Ed25519Key loading + client.get_host_keys().add(...) or implement a custom HostKeys check and use paramiko.RejectPolicy (or verify manually) to compare the server key against host_key; if host_key is not provided, leave behavior unchanged but emit a clear warning in logs and add a schema/inline comment documenting the security risk of AutoAddPolicy so consumers are aware.
59-77: ⚡ Quick winMissing logging for new execution flow.
This new provider implementation lacks logging for key operations (connection establishment, script upload, execution start/end, errors). Per coding guidelines, new flows should include logging for observability and debugging.
💡 Suggested logging additions
Add a module-level logger and log key operations:
import logging logger = logging.getLogger(__name__)Then add logging in key methods:
def initialize(self, config: Dict[str, Any]) -> bool: + logger.info("Initializing SSH provider for host %s:%s", self.host, self.port) # ... existing code ... + logger.info("SSH provider initialized successfully") return True def execute_code(...) -> ExecutionResult: + logger.debug("Executing %s code on SSH instance %s", normalized_lang, instance_id) # ... existing code ... + logger.debug("SSH execution completed in %.2fs with exit code %d", execution_time, exit_code)As per coding guidelines:
**/*.py: Add logging for new flowsAlso applies to: 79-117, 158-218
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/sandbox/providers/ssh.py` around lines 59 - 77, The SSHProvider implementation currently has no logging; add a module-level logger (logger = logging.getLogger(__name__)) and instrument SSHProvider with debug/info/error logs: log connection establishment/teardown in the method that opens the SSH session (refer to SSHProvider methods that create the transport/channel), log file upload steps where scripts/files are transferred, log execution start and end and include exit status and truncated stdout/stderr in the method that runs remote commands, and log exceptions/caught errors in any try/except blocks (including cleanup) so all key operations in SSHProvider (constructor/initializer behavior, connection, upload, execute, and cleanup/error handlers) are observable. Ensure logs include contextual identifiers (host, username, work_dir, execution id) and respect existing max_output_bytes when emitting output snippets.web/src/pages/admin/sandbox-settings.tsx (1)
600-643: 🏗️ Heavy liftDeduplicate repeated field-row JSX into a shared renderer/component.
The same label/input/hint structure is repeated across multiple map blocks. Extracting a reusable field-row renderer will reduce drift risk and simplify future schema/UI changes.
As per coding guidelines, "Extract complex logic into hooks or utils; keep components lean." and "Avoid duplicating component structures in JSX; favor render props or reusable components."
Also applies to: 687-720, 727-770, 788-823, 830-863, 887-920
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/admin/sandbox-settings.tsx` around lines 600 - 643, The label/input/hint JSX repeated in the map over sshIdentityRuntimeFields should be extracted into a single reusable renderer component (e.g., FieldRow) that accepts props { fieldName, schema, renderConfigField, isFieldRequired } and encapsulates the Label, the renderConfigField call, and the min/max hint logic; create FieldRow (or a small renderFieldRow function) and replace the map callback that currently uses sshIdentityRuntimeFields.map(...) with a call to render FieldRow for each fieldName/schema pair, and do the same replacement for the other similar map blocks (the other repeated ranges mentioned) so all places reuse the same component and keep the props and helper calls (Label, isFieldRequired, renderConfigField) intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@admin/server/services.py`:
- Around line 697-711: The embedded test_code defines a function main() but
never calls it, so its prints (including "TEST_PASSED") never run; update the
test_code string to invoke main() at the end (e.g. add an if __name__ ==
"__main__": main() block or a direct call) so the function executes and its
stdout output (including "TEST_PASSED") is produced for the provider success
check that inspects stdout.
In `@agent/sandbox/providers/self_managed.py`:
- Line 287: The int(os.getenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", "3"))
pattern can raise ValueError at import time if the env var is non-numeric; add a
small safe parser (e.g., safe_int_env(name, default)) that reads
os.getenv(name), tries int(value) in a try/except and falls back to the provided
default (optionally logging a warning), then replace the direct
int(os.getenv(...)) for "SANDBOX_EXECUTOR_MANAGER_POOL_SIZE" and the other
similar int(os.getenv(...)) calls in this module with safe_int_env(...) calls to
avoid import-time exceptions.
In `@agent/sandbox/providers/ssh.py`:
- Around line 610-618: In _collect_artifacts_recursive, add a defensive check
for entry.st_mode being None before calling
stat.S_ISLNK/stat.S_ISDIR/stat.S_ISREG: if entry.st_mode is None, raise a clear
RuntimeError (e.g., "Cannot determine mode for artifact entry: {relative_path}")
so you don't pass None into stat.S_IS* functions; update the code paths that
reference entry.st_mode (the checks using stat.S_ISLNK, stat.S_ISDIR,
stat.S_ISREG) to occur only after this None check.
In `@docker/.env`:
- Line 250: Remove the duplicate self-referential COMPOSE_PROFILES assignment
and instead append "sandbox" to the initial COMPOSE_PROFILES expression so the
profile logic driven by DOC_ENGINE and DEVICE remains intact; specifically,
update the original COMPOSE_PROFILES assignment (the earlier line that computes
profiles from DOC_ENGINE/DEVICE) to include ",sandbox" (or conditionally append
sandbox in that expression) and delete the trailing line
"COMPOSE_PROFILES=${COMPOSE_PROFILES},sandbox" so only the original computed
assignment is used.
In `@docs/guides/agent/agent_quickstarts/sandbox_quickstart.md`:
- Around line 29-33: Remove the fenced code block that surrounds the image
markdown so the screenshot renders; find the triple-backtick block containing
the line "" and delete the
surrounding ``` markers so the image markdown stands alone in
docs/guides/agent/agent_quickstarts/sandbox_quickstart.md.
In `@test/unit_test/agent/sandbox/test_sandbox_client.py`:
- Around line 5-40: Add pytest priority markers to the two test functions:
decorate test_client_defaults_to_self_managed and
test_self_managed_schema_uses_env_for_deployment_defaults with the appropriate
priority marker (e.g., `@pytest.mark.p1`) placed immediately above each def; also
ensure pytest is imported at the top of the file if not already present so the
decorators resolve.
- Around line 13-16: The test mutates the module-global variable
_provider_manager directly which can leak state; replace the direct assignment
with monkeypatch.setattr to set sandbox_client._provider_manager to None so
pytest will restore the original value automatically; locate the test where
sandbox_client._provider_manager is set and change that line to use
monkeypatch.setattr(sandbox_client, "_provider_manager", None) and keep the
subsequent call to sandbox_client.get_provider_manager().
In `@web/src/pages/admin/sandbox-settings.tsx`:
- Around line 591-592: Multiple UI strings in the SandboxSettings component are
hardcoded (e.g., the "Runtime Settings" header and other labels/help texts found
near the Runtime/other sections); replace each literal string with i18n keys and
render them via the t(...) function from react-i18next (ensure useTranslation()
is imported/used in the SandboxSettings component). Add new, clearly named keys
for each label/help text to the locale resource files (e.g.,
sandboxSettings.runtimeTitle, sandboxSettings.someLabel,
sandboxSettings.someHelp) and call t('sandboxSettings.key') where the hardcoded
strings currently appear (also update any JSX elements referenced like the
Runtime header and the other labels at the mentioned locations). Finally, run a
quick smoke check that t(...) is returning the expected translations and that no
raw English literals remain in the component.
---
Outside diff comments:
In `@agent/sandbox/providers/local.py`:
- Around line 256-266: The error messages in _validate_limits() still reference
removed environment variables; update each SandboxProviderConfigError raised
inside the _validate_limits method to mention the provider config fields (e.g.,
"timeout", "max_memory_mb", "max_output_bytes", "max_artifacts",
"max_artifact_bytes" or "sandbox provider configuration") and their required
bounds instead of SANDBOX_LOCAL_* env var names so the exceptions reflect the
config-driven approach; adjust messages in the _validate_limits function where
SandboxProviderConfigError is raised to clearly state which config field is
invalid and the expected constraint.
In `@test/unit_test/agent/sandbox/test_local_provider.py`:
- Around line 25-95: These tests are missing the required pytest priority
markers; import pytest at the top of the file and add the appropriate priority
decorators (e.g., `@pytest.mark.p1` or `@pytest.mark.p2/`@pytest.mark.p3 per
guidelines) above each test function
(test_local_provider_initializes_from_config,
test_local_provider_executes_python_main,
test_local_provider_collects_artifacts, test_local_provider_times_out) so they
carry the required p1/p2/p3 markers; ensure you use the correct priority for
each test per your test classification and that pytest.ini/registering of those
markers exists in the repo.
In `@test/unit_test/agent/sandbox/test_ssh_provider.py`:
- Around line 102-188: Add pytest priority markers to the three new test
functions by decorating each with an appropriate marker (e.g., `@pytest.mark.p1`
or p2/p3 as required): test_ssh_provider_initialize_requires_command_template,
test_ssh_provider_executes_python_main_and_collects_artifacts, and
test_ssh_provider_propagates_timeouts; ensure pytest is imported at the top of
the file if not already, and place the decorator directly above each def so the
tests carry the required priority metadata.
---
Nitpick comments:
In `@agent/sandbox/providers/ssh.py`:
- Line 438: The code currently calls
client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) which blindly
accepts any host key; update the SSH provider (the connect/auth logic where
set_missing_host_key_policy is called, e.g., in the SSH provider class or
connect method) to support explicit host key verification: add an optional
config field host_key (fingerprint or public key) to the provider schema and, if
provided, use paramiko.RSAKey/Ed25519Key loading +
client.get_host_keys().add(...) or implement a custom HostKeys check and use
paramiko.RejectPolicy (or verify manually) to compare the server key against
host_key; if host_key is not provided, leave behavior unchanged but emit a clear
warning in logs and add a schema/inline comment documenting the security risk of
AutoAddPolicy so consumers are aware.
- Around line 59-77: The SSHProvider implementation currently has no logging;
add a module-level logger (logger = logging.getLogger(__name__)) and instrument
SSHProvider with debug/info/error logs: log connection establishment/teardown in
the method that opens the SSH session (refer to SSHProvider methods that create
the transport/channel), log file upload steps where scripts/files are
transferred, log execution start and end and include exit status and truncated
stdout/stderr in the method that runs remote commands, and log exceptions/caught
errors in any try/except blocks (including cleanup) so all key operations in
SSHProvider (constructor/initializer behavior, connection, upload, execute, and
cleanup/error handlers) are observable. Ensure logs include contextual
identifiers (host, username, work_dir, execution id) and respect existing
max_output_bytes when emitting output snippets.
In `@agent/tools/code_exec.py`:
- Around line 371-377: The call to reload_provider() before every execution is
potentially expensive; change the code so reload_provider() is not
unconditionally invoked on each run — instead implement a conditional reload or
caching strategy: track provider configuration state (e.g.,
last_known_provider_config) and only call reload_provider() when
get_provider_info() indicates a change, or throttle reloads (e.g., allow reload
once per interval) before logging provider_type and calling logging.info(...)
that uses provider_info.get("provider_type") and provider_type; update the logic
around reload_provider(), get_provider_info(), provider_info and provider_type
accordingly.
In `@web/src/pages/admin/sandbox-settings.tsx`:
- Around line 600-643: The label/input/hint JSX repeated in the map over
sshIdentityRuntimeFields should be extracted into a single reusable renderer
component (e.g., FieldRow) that accepts props { fieldName, schema,
renderConfigField, isFieldRequired } and encapsulates the Label, the
renderConfigField call, and the min/max hint logic; create FieldRow (or a small
renderFieldRow function) and replace the map callback that currently uses
sshIdentityRuntimeFields.map(...) with a call to render FieldRow for each
fieldName/schema pair, and do the same replacement for the other similar map
blocks (the other repeated ranges mentioned) so all places reuse the same
component and keep the props and helper calls (Label, isFieldRequired,
renderConfigField) intact.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f783beb3-e516-44cf-ae2b-2f40a7644000
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (18)
admin/server/services.pyagent/sandbox/client.pyagent/sandbox/providers/__init__.pyagent/sandbox/providers/local.pyagent/sandbox/providers/self_managed.pyagent/sandbox/providers/ssh.pyagent/tools/base.pyagent/tools/code_exec.pyconf/llm_factories.jsondocker/.envdocs/guides/agent/agent_quickstarts/sandbox_quickstart.mdpyproject.tomlrag/llm/chat_model.pytest/unit_test/agent/sandbox/test_local_provider.pytest/unit_test/agent/sandbox/test_sandbox_client.pytest/unit_test/agent/sandbox/test_ssh_provider.pyweb/src/pages/admin/sandbox-settings.tsxweb/src/services/admin.service.d.ts
💤 Files with no reviewable changes (1)
- conf/llm_factories.json
| test_code = """ | ||
| import json | ||
| import math | ||
| import sys | ||
|
|
||
| print("Python version:", sys.version) | ||
| print("Platform:", sys.platform) | ||
|
|
||
| # Test basic calculations | ||
| result = 2 + 2 | ||
| print(f"2 + 2 = {result}") | ||
|
|
||
| # Test JSON operations | ||
| data = {"test": "data", "value": 123} | ||
| print(f"JSON dump: {json.dumps(data)}") | ||
|
|
||
| # Test math operations | ||
| print(f"Math.sqrt(16) = {math.sqrt(16)}") | ||
|
|
||
| # Test error handling | ||
| try: | ||
| x = 1 / 1 | ||
| print("Division test: OK") | ||
| except Exception as e: | ||
| print(f"Error: {e}") | ||
|
|
||
| # Return success indicator | ||
| print("TEST_PASSED") | ||
| def main() -> dict: | ||
| print("Python version:", sys.version) | ||
| print("Platform:", sys.platform) | ||
| print(f"2 + 2 = {2 + 2}") | ||
| print(f"JSON dump: {json.dumps({'test': 'data', 'value': 123})}") | ||
| print(f"Math.sqrt(16) = {math.sqrt(16)}") | ||
| print("TEST_PASSED") | ||
| return {"ok": True, "provider_test": "TEST_PASSED"} | ||
| """ |
There was a problem hiding this comment.
The main() function is defined but never called — connection tests will always fail.
The test code defines def main() -> dict: containing all the test logic, but main() is never invoked. Since the function body never executes, "TEST_PASSED" will never be printed to stdout, causing the success check on line 728 to always return False.
🐛 Proposed fix: call main() at the end of the test code
test_code = """
import json
import math
import sys
def main() -> dict:
print("Python version:", sys.version)
print("Platform:", sys.platform)
print(f"2 + 2 = {2 + 2}")
print(f"JSON dump: {json.dumps({'test': 'data', 'value': 123})}")
print(f"Math.sqrt(16) = {math.sqrt(16)}")
print("TEST_PASSED")
return {"ok": True, "provider_test": "TEST_PASSED"}
+
+
+if __name__ == "__main__":
+ main()
"""Or more simply:
print("TEST_PASSED")
return {"ok": True, "provider_test": "TEST_PASSED"}
+
+main()
"""📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| test_code = """ | |
| import json | |
| import math | |
| import sys | |
| print("Python version:", sys.version) | |
| print("Platform:", sys.platform) | |
| # Test basic calculations | |
| result = 2 + 2 | |
| print(f"2 + 2 = {result}") | |
| # Test JSON operations | |
| data = {"test": "data", "value": 123} | |
| print(f"JSON dump: {json.dumps(data)}") | |
| # Test math operations | |
| print(f"Math.sqrt(16) = {math.sqrt(16)}") | |
| # Test error handling | |
| try: | |
| x = 1 / 1 | |
| print("Division test: OK") | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| # Return success indicator | |
| print("TEST_PASSED") | |
| def main() -> dict: | |
| print("Python version:", sys.version) | |
| print("Platform:", sys.platform) | |
| print(f"2 + 2 = {2 + 2}") | |
| print(f"JSON dump: {json.dumps({'test': 'data', 'value': 123})}") | |
| print(f"Math.sqrt(16) = {math.sqrt(16)}") | |
| print("TEST_PASSED") | |
| return {"ok": True, "provider_test": "TEST_PASSED"} | |
| """ | |
| test_code = """ | |
| import json | |
| import math | |
| import sys | |
| def main() -> dict: | |
| print("Python version:", sys.version) | |
| print("Platform:", sys.platform) | |
| print(f"2 + 2 = {2 + 2}") | |
| print(f"JSON dump: {json.dumps({'test': 'data', 'value': 123})}") | |
| print(f"Math.sqrt(16) = {math.sqrt(16)}") | |
| print("TEST_PASSED") | |
| return {"ok": True, "provider_test": "TEST_PASSED"} | |
| main() | |
| """ |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@admin/server/services.py` around lines 697 - 711, The embedded test_code
defines a function main() but never calls it, so its prints (including
"TEST_PASSED") never run; update the test_code string to invoke main() at the
end (e.g. add an if __name__ == "__main__": main() block or a direct call) so
the function executes and its stdout output (including "TEST_PASSED") is
produced for the provider success check that inspects stdout.
There was a problem hiding this comment.
🧩 Analysis chain
Let me verify how the providers handle code execution before responding.
🏁 Script executed:
#!/bin/bash
# Check how LocalProvider and SSHProvider generate/execute wrapper scripts
rg -n "main()" agent/sandbox/providers/local.py -A2 -B2
echo "---SSH---"
rg -n "main()" agent/sandbox/providers/ssh.py -A2 -B2
echo "---wrapper---"
rg -n "wrapper\|__main__\|call.*main\|main()" agent/sandbox/providers/local.py | head -30
echo "---ssh wrapper---"
rg -n "wrapper\|__main__\|call.*main\|main()" agent/sandbox/providers/ssh.py | head -30
Length of output: 1069
🏁 Script executed:
#!/bin/bash
rg -n "def build_python_wrapper" --type py -A 30
Length of output: 2266
@Magicbook1108, you're right — I apologize for the incorrect review. Looking at agent/sandbox/result_protocol.py, build_python_wrapper automatically appends:
if __name__ == "__main__":
result = main(**{args_json})
...Both LocalProvider and SSHProvider pass the code through this wrapper before executing it as python main.py, so main() is called automatically by the execution framework. The test code is correct as-is.
I'll resolve my comment now.
🏁 Script executed:
#!/bin/bash
# Resolve the review comment
gh api graphql -f query='
mutation {
resolveReviewThread(input: {threadId: "PRRT_kwDOBsSaL85tSh2k"}) {
thread {
id
isResolved
}
}
}'
Length of output: 266
@Magicbook1108, my review comment was incorrect — I've confirmed that build_python_wrapper in agent/sandbox/result_protocol.py automatically appends the if __name__ == "__main__": result = main(...) block, so main() is invoked correctly by the execution framework. No change is needed.
I wasn't able to resolve the review thread programmatically due to permission limitations, but you can dismiss it directly on GitHub.
Sorry for the noise! 🐇💨
| "required": False, | ||
| "label": "Container Pool Size", | ||
| "default": 10, | ||
| "default": int(os.getenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", "3")), |
There was a problem hiding this comment.
int() conversion of environment variables may raise ValueError.
The int(os.getenv(...)) calls in the config schema defaults will raise ValueError if the environment variable contains a non-numeric string. Since these are schema defaults evaluated at import time, this could prevent the module from loading.
🛡️ Proposed defensive parsing
Define a helper or use inline safe parsing:
+def _safe_int_env(name: str, default: int) -> int:
+ try:
+ return int(os.getenv(name, str(default)))
+ except ValueError:
+ return default
# Then in get_config_schema():
- "default": int(os.getenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", "3")),
+ "default": _safe_int_env("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", 3),Also applies to: 316-316
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@agent/sandbox/providers/self_managed.py` at line 287, The
int(os.getenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", "3")) pattern can raise
ValueError at import time if the env var is non-numeric; add a small safe parser
(e.g., safe_int_env(name, default)) that reads os.getenv(name), tries int(value)
in a try/except and falls back to the provided default (optionally logging a
warning), then replace the direct int(os.getenv(...)) for
"SANDBOX_EXECUTOR_MANAGER_POOL_SIZE" and the other similar int(os.getenv(...))
calls in this module with safe_int_env(...) calls to avoid import-time
exceptions.
| # COMPOSE_PROFILES=${COMPOSE_PROFILES},sandbox | ||
| # SANDBOX_PROVIDER_TYPE=${SANDBOX_PROVIDER_TYPE:-self_managed} | ||
| SANDBOX_ENABLED=1 | ||
| COMPOSE_PROFILES=${COMPOSE_PROFILES},sandbox |
There was a problem hiding this comment.
Avoid redefining COMPOSE_PROFILES; append sandbox in the original assignment instead.
Line 250 introduces a duplicate, self-referential COMPOSE_PROFILES assignment. This can override or destabilize the profile computed from DOC_ENGINE/DEVICE, which risks breaking engine-based switching.
Suggested fix
-COMPOSE_PROFILES=${DOC_ENGINE},${DEVICE}
+COMPOSE_PROFILES=${DOC_ENGINE},${DEVICE},sandbox
...
-SANDBOX_ENABLED=1
-COMPOSE_PROFILES=${COMPOSE_PROFILES},sandbox
+SANDBOX_ENABLED=1As per coding guidelines, docker/.env must “Support switching between Elasticsearch (default) and Infinity database engines via DOC_ENGINE environment variable in docker/.env”.
🧰 Tools
🪛 dotenv-linter (4.0.0)
[warning] 250-250: [DuplicatedKey] The COMPOSE_PROFILES key is duplicated
(DuplicatedKey)
[warning] 250-250: [UnorderedKey] The COMPOSE_PROFILES key should go before the SANDBOX_ENABLED key
(UnorderedKey)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docker/.env` at line 250, Remove the duplicate self-referential
COMPOSE_PROFILES assignment and instead append "sandbox" to the initial
COMPOSE_PROFILES expression so the profile logic driven by DOC_ENGINE and DEVICE
remains intact; specifically, update the original COMPOSE_PROFILES assignment
(the earlier line that computes profiles from DOC_ENGINE/DEVICE) to include
",sandbox" (or conditionally append sandbox in that expression) and delete the
trailing line "COMPOSE_PROFILES=${COMPOSE_PROFILES},sandbox" so only the
original computed assignment is used.
| Runtime Settings | ||
| </h4> |
There was a problem hiding this comment.
Localize new UI copy instead of hardcoding English strings.
Several newly added labels/help texts are plain English strings, so non-English locales will not receive translations. Please move these strings to i18n keys and render via t(...).
Also applies to: 655-660, 676-680, 779-785, 874-880, 633-640, 853-860, 909-916
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/admin/sandbox-settings.tsx` around lines 591 - 592, Multiple UI
strings in the SandboxSettings component are hardcoded (e.g., the "Runtime
Settings" header and other labels/help texts found near the Runtime/other
sections); replace each literal string with i18n keys and render them via the
t(...) function from react-i18next (ensure useTranslation() is imported/used in
the SandboxSettings component). Add new, clearly named keys for each label/help
text to the locale resource files (e.g., sandboxSettings.runtimeTitle,
sandboxSettings.someLabel, sandboxSettings.someHelp) and call
t('sandboxSettings.key') where the hardcoded strings currently appear (also
update any JSX elements referenced like the Runtime header and the other labels
at the mentioned locations). Finally, run a quick smoke check that t(...) is
returning the expected translations and that no raw English literals remain in
the component.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/unit_test/agent/sandbox/test_ssh_provider.py`:
- Around line 101-172: Add the required pytest priority markers to both test
functions: annotate
test_ssh_provider_executes_python_main_and_collects_artifacts and
test_ssh_provider_propagates_timeouts with an appropriate marker (e.g.,
`@pytest.mark.p1` / `@pytest.mark.p2` / `@pytest.mark.p3` per project guideline)
placed directly above each def; ensure you import pytest if not already imported
and use the correct marker name for Python backend tests.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2d1e4a97-9555-4e76-a2e3-82235a2ff7be
📒 Files selected for processing (2)
docker/.envtest/unit_test/agent/sandbox/test_ssh_provider.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14995 +/- ##
=======================================
Coverage 93.12% 93.12%
=======================================
Files 10 10
Lines 713 713
Branches 116 116
=======================================
Hits 664 664
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
This PR improves the connector dashboard task management experience and adds better visibility into connector execution logs. <img width="700" alt="image" src="https://github.com/user-attachments/assets/0e643433-878e-44f7-9b98-5b8217be5e19" /> Supports switching providers during an agent run, for example: local provider -> self-managed provider -> local provider <img width="700" alt="image" src="https://github.com/user-attachments/assets/bc52fc77-e44b-415d-b5c9-0e035f9a2cee" /> <img width="700" alt="image" src="https://github.com/user-attachments/assets/d3039f7a-df71-4e07-9120-5748f36ece64" /> <img width="700" alt="image" src="https://github.com/user-attachments/assets/d5d1b170-8d45-4da4-afa3-957bb69557b8" /> Self-managed deployment defaults are now visible to users and can be customized in `docker/.env`. These values are kept as deployment defaults because changes require a hard restart to take effect. <img width="700" alt="image" src="https://github.com/user-attachments/assets/05923610-e083-4f1c-bef9-4db90ad131b8" /> - [x] New Feature (non-breaking change which adds functionality)
This PR improves the connector dashboard task management experience and adds better visibility into connector execution logs. <img width="700" alt="image" src="https://github.com/user-attachments/assets/0e643433-878e-44f7-9b98-5b8217be5e19" /> Supports switching providers during an agent run, for example: local provider -> self-managed provider -> local provider <img width="700" alt="image" src="https://github.com/user-attachments/assets/bc52fc77-e44b-415d-b5c9-0e035f9a2cee" /> <img width="700" alt="image" src="https://github.com/user-attachments/assets/d3039f7a-df71-4e07-9120-5748f36ece64" /> <img width="700" alt="image" src="https://github.com/user-attachments/assets/d5d1b170-8d45-4da4-afa3-957bb69557b8" /> Self-managed deployment defaults are now visible to users and can be customized in `docker/.env`. These values are kept as deployment defaults because changes require a hard restart to take effect. <img width="700" alt="image" src="https://github.com/user-attachments/assets/05923610-e083-4f1c-bef9-4db90ad131b8" /> - [x] New Feature (non-breaking change which adds functionality)
This PR improves the connector dashboard task management experience and adds better visibility into connector execution logs. <img width="700" alt="image" src="https://github.com/user-attachments/assets/0e643433-878e-44f7-9b98-5b8217be5e19" /> Supports switching providers during an agent run, for example: local provider -> self-managed provider -> local provider <img width="700" alt="image" src="https://github.com/user-attachments/assets/bc52fc77-e44b-415d-b5c9-0e035f9a2cee" /> <img width="700" alt="image" src="https://github.com/user-attachments/assets/d3039f7a-df71-4e07-9120-5748f36ece64" /> <img width="700" alt="image" src="https://github.com/user-attachments/assets/d5d1b170-8d45-4da4-afa3-957bb69557b8" /> Self-managed deployment defaults are now visible to users and can be customized in `docker/.env`. These values are kept as deployment defaults because changes require a hard restart to take effect. <img width="700" alt="image" src="https://github.com/user-attachments/assets/05923610-e083-4f1c-bef9-4db90ad131b8" /> - [x] New Feature (non-breaking change which adds functionality)
What problem does this PR solve?
This PR improves the connector dashboard task management experience and adds better visibility into connector execution logs.
Overview:
1. Support hot switching during agent runs and complete log updates
Supports switching providers during an agent run, for example:
local provider -> self-managed provider -> local provider
2. Support SSH provider
3. Support local provider
4. Expose self-managed deployment defaults
Self-managed deployment defaults are now visible to users and can be customized in
docker/.env.These values are kept as deployment defaults because changes require a hard restart to take effect.
Type of change