feat(claw): run bash on an ssh login, no daemon on the far end

The framework ships rhema-sandbox-ssh; the claw's sandbox seam now
wires it as a third kind beside local and http. The ssh choice carries
a host (any destination the local ssh config resolves) and a workspace
base, default /root, with one directory per claw workspace under it so
two sessions never share a root. The seed probe makes the root first
and quotes it for the remote bash. The settings screen gains the SSH
host card, and /v1/sandbox carries host and workspace.

The rhema family moves to 0.4.1 in lockstep to pick the crate up.
This commit is contained in:
vhaudiquet committed 2026-11-22 02:39:00 +01:00
1 parent f779415b2b
commit cdeb5c3994
13 files changed
+548 -139

No files matched your search

+19 -18
View File
@@ -29,33 +29,34 @@ mock = ["rhema-core/mock"]
# shell, the approval seam, and revive-on-resume (rhema-bash), the
# system-prompt renderer (rhema-prompt), and the driver that turns a
# provider into a host-operating agent (rhema-host-agent)
rhema-bash = "0.4.0"
rhema-prompt = "0.4.0"
rhema-host-agent = "0.4.0"
rhema-autonomous-agent = "0.4.0"
rhema-config = "0.4.0"
rhema-core = "0.4.0"
rhema-bash = "0.4.1"
rhema-prompt = "0.4.1"
rhema-host-agent = "0.4.1"
rhema-autonomous-agent = "0.4.1"
rhema-config = "0.4.1"
rhema-core = "0.4.1"
# The bounded request view over the claw sessions, on by default here
rhema-transcript = "0.4.0"
rhema-transcript = "0.4.1"
rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" }
rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" }
# The accounts layer: identities hold the forge tokens the watches poll
# with, and the identity tools manage them over chat
rhema-identity = "0.4.0"
rhema-rsd = "0.4.0"
# The sandbox seam: where `bash` runs, local process or a daemon speaking
# the wire protocol over HTTP
rhema-sandbox = "0.4.0"
rhema-sandbox-http = "0.4.0"
rhema-identity = "0.4.1"
rhema-rsd = "0.4.1"
# The sandbox seam: where `bash` runs, this host's processes, a daemon
# speaking the wire protocol over HTTP, or an ssh login on a far box
rhema-sandbox = "0.4.1"
rhema-sandbox-http = "0.4.1"
rhema-sandbox-ssh = "0.4.1"
# The tool contract: the agent-token allowlist and version the auth
# middleware enforces (rhema-tools spec). The arrow runs claw ->
# contract only — never the reverse.
rhema-claw-tools-contract = { path = "../../tools/contract" }
# The resident tier's durable memory: its tools join the resolver chain
rhema-memory = "0.4.0"
rhema-memory = "0.4.1"
# The shared ModelCard the backend registry's listings return
rhema-provider = "0.4.0"
rhema-provider-registry = "0.4.0"
rhema-provider = "0.4.1"
rhema-provider-registry = "0.4.1"
# Args for the two-flag binary surface
clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true }
@@ -80,7 +81,7 @@ time = { version = "0.3", default-features = false, features = ["parsing"] }
# Inbound chat images ride base64; the dispatch decodes them into the
# attachment store
base64 = "0.22"
rhema-mcp = "0.4.0"
rhema-mcp = "0.4.1"
[dev-dependencies]
tempfile = "3"
@@ -92,7 +93,7 @@ reqwest = { version = "0.12", features = ["json", "stream"] }
bytes = "1"
# The scripted provider for turn-level tests; mirrors rhema-code's mock
# feature without a feature of our own — tests are the only consumer
rhema-core = { version = "0.4.0", features = ["mock"] }
rhema-core = { version = "0.4.1", features = ["mock"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
[lints]
+13 -6
View File
@@ -70,9 +70,11 @@ token: change-me # optional; when set, /v1/* requires it
agent_token: change-me-too # the client tools' scoped bearer (rhema-tools)
tools_bin: ~/.local/share/rhema-tools/bin # put the client tools on PATH
sandbox: # where bash runs; omit for this host
kind: http # local (default) or http
url: https://box.example:7600 # the sandboxd base URL
token: sandbox-secret # the daemon's shared secret, if it has one
kind: ssh # local (default), http, or ssh
host: me@box.example # the ssh destination: an alias or user@host
workspace: /srv/claw # ssh only: the workspace base, default /root
# http instead speaks the sandbox protocol (rhema-sandboxd):
# kind: http, url: https://box.example:7600, token: sandbox-secret
poll_interval_secs: 120
max_turn_steps: 2048 # tool rounds one chat turn may run
watches: # a seed: imported while the table is empty
@@ -103,10 +105,15 @@ conversation intact; a follow-up message keeps going.
`sandbox` selects where the agent's `bash` runs. Unset or `kind: local`
keeps the daemon's own processes. `kind: http` sends commands to a host
speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an
optional `token`. The settings screen writes the same choice to the
optional `token`. `kind: ssh` runs commands on a login the local `ssh`
config resolves (`host`, any alias or `user@host`), nothing installed
on the far end; `workspace` names the remote directory the claw's
workspaces live under, `/root` by default, one directory per claw
workspace under it. The settings screen writes the same choice to the
settings table, and the next turn reads it; no restart is needed. On
first use the claw copies the local workspace into the sandbox's
`/workspace`. Later edits stay there; the claw does not copy them back.
workspace root. Later edits stay there; the claw does not copy them
back.
The surface refuses to start on a non-loopback `listen` with no
`token`: anything beyond loopback can reach the port, and the bearer
@@ -150,7 +157,7 @@ GET /v1/attachments/{id} an attached file's bytes
GET /v1/phone/commands?device= the device's queued, unconfirmed commands
POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report
GET /v1/sandbox where the agent's bash runs
PUT /v1/sandbox {"kind","url"?,"token"?}, switch and persist
PUT /v1/sandbox {"kind","url"?,"token"?,"host"?,"workspace"?}, switch and persist
GET /v1/providers the backend instances + the active pair
PUT /v1/providers/active {"provider","model"?} — switch, persisted
PUT /v1/providers/{id}/credentials add or replace an instance, persisted
+35 -2
View File
@@ -464,6 +464,15 @@ sandbox:
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http);
assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600"));
assert_eq!(sandbox.token.as_deref(), Some("sandbox-secret"));
let config: ClawConfig = serde_yaml::from_str(
"sandbox:\n kind: ssh\n host: me@box.example\n workspace: /srv/claw\n",
)
.expect("the ssh sandbox parses");
let sandbox = config.sandbox.expect("the sandbox parses");
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Ssh);
assert_eq!(sandbox.host.as_deref(), Some("me@box.example"));
assert_eq!(sandbox.workspace.as_deref(), Some("/srv/claw"));
}
#[test]
@@ -472,7 +481,7 @@ sandbox:
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: None,
token: None,
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
@@ -484,13 +493,37 @@ sandbox:
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: Some("https://box.example:7600".to_owned()),
token: None,
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a complete remote choice passes");
}
#[test]
fn an_ssh_sandbox_needs_a_host_at_boot() {
let missing = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
"an ssh sandbox without a host is refused at boot"
);
let valid = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
host: Some("me@box.example".to_owned()),
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a bare login is all ssh needs");
}
#[test]
fn an_unknown_key_is_rejected_and_named() {
let err = serde_yaml::from_str::<ClawConfig>("listne: 127.0.0.1:7799\n")
+10
View File
@@ -2016,6 +2016,8 @@ fn sandbox_json(state: &ClawState) -> Value {
"kind": choice.kind.as_str(),
"url": choice.url,
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()),
"host": choice.host,
"ssh_workspace": choice.workspace,
"workspace": state.sandbox().workspace().display().to_string(),
"local_workspace": state.sandbox().local_workspace().display().to_string(),
"remote_workspace": crate::sandbox::REMOTE_WORKSPACE,
@@ -2051,6 +2053,14 @@ async fn sandbox_put(
.map(str::to_owned)
.or_else(|| current.url.clone()),
token,
host: body["host"]
.as_str()
.map(str::to_owned)
.or_else(|| current.host.clone()),
workspace: body["workspace"]
.as_str()
.map(str::to_owned)
.or_else(|| current.workspace.clone()),
};
state.sandbox().set(choice).map_err(|err| match err {
crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
+241 -44
View File
@@ -1,16 +1,18 @@
//! Where the claw's `bash` runs: this host's processes, or a daemon
//! speaking the sandbox protocol over HTTP.
//! Where the claw's `bash` runs: this host's processes, a daemon
//! speaking the sandbox protocol over HTTP, or an ssh login on a far
//! box.
//!
//! The choice is deployment state, persisted in the settings table and
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`
//! and gives the handlers a `ShellSandbox` executor over it. The tool
//! spec, approval gate, output caps, and error shaping stay in
//! `ShellTools`; only the machine changes.
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`.
//! `ssh` builds an `SshSandbox` on a destination the local ssh config
//! resolves, no daemon on the far end. The tool spec, approval gate,
//! output caps, and error shaping stay in `ShellTools`; only the
//! machine changes.
//!
//! A remote sandbox starts empty. On the first command for a
//! workspace, the executor probes `/workspace` and, when it is empty,
//! sends the host workspace as a tarball through the protocol's seed
//! workspace, the executor probes the workspace root and, when it is
//! empty, sends the host workspace as a tarball through the seed
//! route. Later edits stay in the sandbox; the claw does not copy them
//! back.
@@ -25,6 +27,7 @@ use base64::Engine as _;
use rhema_bash::exec::{Executed, ShellError, ShellExecutor, default_executor_with};
use rhema_sandbox::{ExecRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_sandbox_http::HttpSandbox;
use rhema_sandbox_ssh::SshSandbox;
use serde::{Deserialize, Serialize};
use crate::settings::SettingsStore;
@@ -32,10 +35,15 @@ use crate::settings::SettingsStore;
/// The settings key the chosen sandbox is persisted under.
pub const SANDBOX_KEY: &str = "sandbox";
/// The workspace path a remote sandbox exposes: one root per session,
/// The workspace path the http sandbox exposes: one root per session,
/// fixed by the protocol.
pub const REMOTE_WORKSPACE: &str = "/workspace";
/// The ssh sandbox's default workspace base: the remote login's own
/// home, the ssh backend's documented default. One directory per claw
/// workspace lands under it, named by the session hash.
pub const SSH_WORKSPACE_ROOT: &str = "/root";
/// The per-command budget of the emptiness probe before a seed: long
/// enough for a fresh sandbox, short enough that an unreachable daemon
/// fails the turn rather than stalling it.
@@ -50,6 +58,8 @@ pub enum SandboxKind {
Local,
/// A host speaking the sandbox protocol over HTTP.
Http,
/// A remote login reached with `ssh`, no daemon on the far end.
Ssh,
}
impl SandboxKind {
@@ -58,6 +68,7 @@ impl SandboxKind {
match self {
Self::Local => "local",
Self::Http => "http",
Self::Ssh => "ssh",
}
}
@@ -67,6 +78,7 @@ impl SandboxKind {
match value {
"local" => Some(Self::Local),
"http" => Some(Self::Http),
"ssh" => Some(Self::Ssh),
_ => None,
}
}
@@ -86,6 +98,14 @@ pub struct SandboxChoice {
/// The shared secret the daemon checks, when it guards its routes.
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
/// The `ssh` sandbox's destination, passed to `ssh` as-is: any
/// alias or `user@host` the local config resolves.
#[serde(skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
/// The `ssh` sandbox's workspace base, where the per-workspace
/// directories land. Defaults to [`SSH_WORKSPACE_ROOT`].
#[serde(skip_serializing_if = "Option::is_none")]
pub workspace: Option<String>,
}
impl SandboxChoice {
@@ -101,6 +121,32 @@ impl SandboxChoice {
.token
.map(|token| token.trim().to_owned())
.filter(|token| !token.is_empty());
self.host = self
.host
.map(|host| host.trim().to_owned())
.filter(|host| !host.is_empty());
self.workspace = self
.workspace
.map(|workspace| workspace.trim().trim_end_matches('/').to_owned())
.filter(|workspace| !workspace.is_empty());
if self.kind == SandboxKind::Ssh {
let host = self
.host
.as_deref()
.ok_or_else(|| SandboxError::Invalid("the ssh sandbox needs a host".to_owned()))?;
if host.contains(char::is_whitespace) {
return Err(SandboxError::Invalid(
"the ssh sandbox host is one destination, no spaces".to_owned(),
));
}
if let Some(workspace) = self.workspace.as_deref()
&& !workspace.starts_with('/')
{
return Err(SandboxError::Invalid(
"the ssh sandbox workspace must be an absolute path".to_owned(),
));
}
}
if self.kind == SandboxKind::Http {
let url = self
.url
@@ -117,7 +163,22 @@ impl SandboxChoice {
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.kind == SandboxKind::Http
self.kind != SandboxKind::Local
}
/// The remote directory one workspace's commands run in: the
/// protocol root for `http`, a directory per host workspace under
/// the configured base for `ssh`.
pub fn remote_root(&self, host: &Path) -> PathBuf {
match self.kind {
SandboxKind::Http => PathBuf::from(REMOTE_WORKSPACE),
SandboxKind::Ssh => PathBuf::from(format!(
"{}/{}",
self.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT),
session_name(host)
)),
SandboxKind::Local => host.to_path_buf(),
}
}
}
@@ -139,7 +200,7 @@ pub struct SandboxState {
settings: Arc<SettingsStore>,
local_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
remote: Mutex<HashMap<String, Arc<HttpSandbox>>>,
remote: Mutex<HashMap<String, Arc<dyn Sandbox>>>,
}
impl SandboxState {
@@ -204,13 +265,9 @@ impl SandboxState {
}
/// The workspace a handler should name and start commands in: the
/// host path locally, `/workspace` on a remote sandbox.
/// host path locally, the choice's remote root otherwise.
pub fn workspace_for(&self, host: &Path) -> PathBuf {
if self.is_remote() {
PathBuf::from(REMOTE_WORKSPACE)
} else {
host.to_path_buf()
}
self.choice().remote_root(host)
}
/// The chat workspace under the current choice, for the settings
@@ -239,18 +296,14 @@ impl SandboxState {
})
}
/// The cached HTTP client for one session. The map is cleared
/// whenever the choice changes, so a new URL or token builds a new
/// client.
/// The cached sandbox for one session. The map is cleared whenever
/// the choice changes, so a new URL, token, host, or base builds a
/// new client.
fn remote_sandbox(
&self,
choice: &SandboxChoice,
host: &Path,
) -> Result<Arc<HttpSandbox>, ShellError> {
let url = choice
.url
.as_deref()
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
) -> Result<Arc<dyn Sandbox>, ShellError> {
let session = session_name(host);
{
let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner);
@@ -258,8 +311,31 @@ impl SandboxState {
return Ok(sandbox.clone());
}
}
let token = choice.token.as_deref().unwrap_or("");
let sandbox = Arc::new(HttpSandbox::new(url.to_owned(), &session, token));
let sandbox: Arc<dyn Sandbox> = match choice.kind {
SandboxKind::Http => {
let url = choice
.url
.as_deref()
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
let token = choice.token.as_deref().unwrap_or("");
Arc::new(HttpSandbox::new(url.to_owned(), &session, token))
}
SandboxKind::Ssh => {
let dest = choice
.host
.as_deref()
.ok_or_else(|| ShellError::Failed("the ssh sandbox has no host".to_owned()))?;
let base = choice.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT);
Arc::new(
SshSandbox::new(dest.to_owned()).with_workspace(format!("{base}/{session}")),
)
}
SandboxKind::Local => {
return Err(ShellError::Failed(
"the local sandbox needs no remote client".to_owned(),
));
}
};
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
@@ -280,20 +356,32 @@ struct ClawShell {
}
impl ClawShell {
/// Seeds the sandbox once per choice. An empty `/workspace` gets
/// Seeds the sandbox once per choice. An empty workspace root gets
/// the host workspace as a tarball; a non-empty one is left alone
/// so a restart never overwrites work done in the sandbox.
/// so a restart never overwrites work done in the sandbox. The
/// probe makes the root first: the http daemon keeps one, the ssh
/// far end has none until something makes it, and the unpack's
/// `tar -C` would fail on a missing directory.
async fn seed(
&self,
sandbox: &Arc<HttpSandbox>,
sandbox: &Arc<dyn Sandbox>,
cancelled: &AtomicBool,
) -> Result<(), ShellError> {
let root = self
.state
.workspace_for(&self.host_workspace)
.to_string_lossy()
.to_string();
let mut sink = |_line: &str| {};
let probe = sandbox
.exec(
ExecRequest {
command: "ls -A /workspace 2>/dev/null | head -n 1".to_owned(),
cwd: REMOTE_WORKSPACE.to_owned(),
command: format!(
"mkdir -p {}; ls -A {} 2>/dev/null | head -n 1",
shquote(&root),
shquote(&root)
),
cwd: root.clone(),
timeout: PROBE_TIMEOUT,
},
cancelled,
@@ -353,15 +441,9 @@ impl ShellExecutor for ClawShell {
self.seed(&sandbox, cancelled).await?;
self.seeded.store(true, Ordering::Relaxed);
}
let sandbox: Arc<dyn Sandbox> = sandbox;
let root = choice.remote_root(&self.host_workspace);
ShellSandbox::new(sandbox)
.run(
command,
Path::new(REMOTE_WORKSPACE),
timeout,
cancelled,
progress,
)
.run(command, &root, timeout, cancelled, progress)
.await
}
}
@@ -379,6 +461,13 @@ fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
}
}
/// One path quoted for the remote `bash -c`: single quotes, the
/// closing quote spliced, good for every path a workspace root can
/// have.
fn shquote(path: &str) -> String {
format!("'{}'", path.replace('\'', "'\\''"))
}
/// The sandbox session name for one host workspace: a stable FNV-1a
/// hash of the path, so the daemon can multiplex one root per session
/// and a restart finds the same root.
@@ -458,7 +547,7 @@ mod tests {
let missing = SandboxChoice {
kind: SandboxKind::Http,
url: None,
token: None,
..SandboxChoice::default()
}
.normalized();
assert!(missing.is_err(), "a URL is required");
@@ -466,18 +555,63 @@ mod tests {
let relative = SandboxChoice {
kind: SandboxKind::Http,
url: Some("box.example:7600".to_owned()),
token: None,
..SandboxChoice::default()
}
.normalized();
assert!(relative.is_err(), "a bare host is not a URL");
}
#[test]
fn an_ssh_choice_needs_a_host_and_an_absolute_base() {
let missing = SandboxChoice {
kind: SandboxKind::Ssh,
..SandboxChoice::default()
}
.normalized();
assert!(missing.is_err(), "a host is required");
let spaced = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me @box".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(spaced.is_err(), "a destination is one word");
let relative = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("srv/claw".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(relative.is_err(), "the base is an absolute path");
let good = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some(" me@box ".to_owned()),
workspace: Some("/srv/claw/".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("the choice normalizes");
assert_eq!(good.host.as_deref(), Some("me@box"));
assert_eq!(good.workspace.as_deref(), Some("/srv/claw"));
assert!(good.is_remote());
assert_eq!(good.kind.as_str(), "ssh");
assert_eq!(
SandboxKind::parse("ssh"),
Some(SandboxKind::Ssh),
"the stored spelling round-trips"
);
}
#[test]
fn the_remote_workspace_is_the_sandbox_root() {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some("http://box:7600/".to_owned()),
token: None,
..SandboxChoice::default()
});
assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE));
assert_eq!(
@@ -487,6 +621,36 @@ mod tests {
);
}
#[test]
fn an_ssh_workspace_is_one_directory_per_host_workspace() {
let host = PathBuf::from("/state/claw/workspaces/interactive");
let choice = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
};
let root = choice.remote_root(&host);
let root = root.to_string_lossy().to_string();
assert!(
root.starts_with("/srv/claw/rhema-claw-"),
"the root lives under the configured base: {root}"
);
assert_eq!(root.len(), "/srv/claw/rhema-claw-".len() + 16);
let default_root = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
..SandboxChoice::default()
}
.remote_root(&host);
assert_eq!(
default_root.to_string_lossy(),
format!("/root/{}", session_name(&host)),
"the base defaults to the login's home"
);
}
#[test]
fn a_choice_persists_and_reloads() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
@@ -504,6 +668,7 @@ mod tests {
kind: SandboxKind::Http,
url: Some("https://box:7600".to_owned()),
token: Some("secret".to_owned()),
..SandboxChoice::default()
})
.expect("the choice saves");
@@ -515,6 +680,38 @@ mod tests {
assert_eq!(reloaded.choice().token.as_deref(), Some("secret"));
}
#[test]
fn an_ssh_choice_persists_with_its_host_and_base() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
let state = SandboxState::load(
settings.clone(),
None,
PathBuf::from("/tmp/ws"),
&BTreeMap::new(),
)
.expect("the state loads");
state
.set(SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
})
.expect("the choice saves");
let reloaded =
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
.expect("the state reloads");
assert_eq!(reloaded.choice().kind, SandboxKind::Ssh);
assert_eq!(reloaded.choice().host.as_deref(), Some("me@box"));
assert_eq!(reloaded.choice().workspace.as_deref(), Some("/srv/claw"));
assert_eq!(
reloaded.workspace().to_string_lossy(),
format!("/srv/claw/{}", session_name(Path::new("/tmp/ws"))),
"the settings surface reports the session root"
);
}
#[tokio::test]
async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() {
let server = MockServer::start().await;
@@ -556,7 +753,7 @@ mod tests {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some(server.uri()),
token: None,
..SandboxChoice::default()
});
let executor = state.executor(dir.path());
let cancelled = AtomicBool::new(false);
+60
View File
@@ -2431,6 +2431,66 @@ async fn the_sandbox_choice_is_listed_and_switchable() {
assert_eq!(cleared["url"], "https://box.example:7600");
}
/// The ssh sandbox over the surface: a choice without a host is a 400,
/// a complete one lists its host and reports the workspace under the
/// configured base, and switching back to this host keeps the ssh
/// fields staged for the next switch.
#[tokio::test]
async fn the_ssh_sandbox_is_switchable_over_the_surface() {
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let refused = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh"}))
.send()
.await
.expect("the refusal posts");
assert_eq!(refused.status(), 400, "an ssh choice without a host");
let switched: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh", "host": "me@box.example", "workspace": "/srv/claw"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(switched["kind"], "ssh");
assert_eq!(switched["host"], "me@box.example");
let workspace = switched["workspace"].as_str().expect("the workspace reads");
assert!(
workspace.starts_with("/srv/claw/rhema-claw-"),
"the workspace sits under the configured base: {workspace}"
);
// Back to this host: the workspace flips, the ssh fields stay
// staged for the next switch.
let local: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(local["kind"], "local");
assert_eq!(local["host"], "me@box.example");
assert!(
local["workspace"].as_str().expect("the workspace reads") != workspace,
"the workspace path follows the choice"
);
}
/// The agent identity surface: the text fields round-trip with
/// partial-save semantics (an absent field is left alone, an empty one
/// clears), the avatar uploads and serves back with its content type,